Loading...
Searching...
No Matches
BMA.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// Bayesian Model Averaging predict path. Carved out of the monolithic
6// GaussianProcessRegression.cpp; same translation-unit-private helpers,
7// same public method definitions, no behaviour change.
8
9#include <Eigen/Cholesky>
10#include <Eigen/Core>
11#include <cmath>
12#include <mutex>
13#include <tuple>
14
19#include "Helpers.h"
20
21namespace gpr {
22
23using detail::writeBMAOutput;
24
25bool GaussianProcessRegression::runBMAGrid(Observation& image1,
26 BMAPrediction& pred_out)
27{
28 // Bayesian Model Averaging gold-standard reference path. Marginalises
29 // the predictive distribution over a 2D log10 grid
30 // (lengthscale x noise_var) weighted by p(theta_k | D) ~
31 // exp(-NLML(theta_k)). The mean and variance fields of the returned
32 // BMAPrediction are paired (E[mu | y], E[var | y] + Var[mu | y]).
33 //
34 // Per-call cost is n_grid noiseless Cholesky decompositions over
35 // R_matrix (intentional: BMA is the validation reference for the
36 // LAPLACE mixture, not the production predict path).
37 //
38 // Returns false if the grid cannot be evaluated (no training data,
39 // missing kernel, empty y, mismatched output shape); the caller is
40 // expected to fall back to MAP in that case.
41 if (R_matrix.size() == 0 || sexpat_cov_func == nullptr) return false;
42
43 const Index_t N_im = static_cast<Index_t>(image1.R.rows());
44 const Index_t D = static_cast<Index_t>(image1.R.cols());
45 EigenMatrix R_mod;
46 Eigen::VectorXd R_mod_ind;
47 aux::AuxiliaryFunctionality aux_func;
48 aux_func.assembleMatrixOfRepetitiveCoordinates(image1.R, R_mod, R_mod_ind);
49
50 // Snapshot kernel state; the builder lambda mutates (lengthScale,
51 // sigma2) per grid point and the dtor restores at scope exit so
52 // MAP-path callers see the original kernel.
53 laplace::ScopedKernelState guard(*sexpat_cov_func, sigma2,
54 lik_gaussian.get());
55
56 // Centre the BMA grid on the current MAP theta_*. Log10 spans:
57 // lengthScale in [log10(ls*) - 1, log10(ls*) + 1] (5 points)
58 // noise in [log10(sn^2*) - 2, log10(sn^2*) + 0] (5 points)
59 // n_grid = 25 grid points = 25 Cholesky decompositions per BMA
60 // call. The grid is evaluated fresh on every invocation.
61 const auto& ls_ref = sexpat_cov_func->getLengthScaleRef();
62 const double ls_star =
63 (ls_ref.size() > 0 && ls_ref(0, 0) > 0.0) ? ls_ref(0, 0) : 1.0;
64 const double sn2_star = (sigma2 > 0.0) ? sigma2 : 1e-6;
65 const double log_ls_centre = std::log10(ls_star);
66 const double log_sn_centre = std::log10(sn2_star);
67 BayesianModelAveraging bma;
68 bma.setGrid(log_ls_centre - 1.0, log_ls_centre + 1.0, 5,
69 log_sn_centre - 2.0, log_sn_centre + 0.0, 5);
70
71 // KernelBuilder: for each (ls, noise_var) pair, set the kernel
72 // hyperparameters then assemble the noiseless training kernel,
73 // the cross-covariance to the query points, and the test diagonal.
74 // BMA::predict adds the noise diagonal itself.
75 // BayesianModelAveraging::fit calls the builder from an OpenMP loop.
76 // The assembly reads the model's kernel, its sigma2 and its geometry
77 // caches, and a kernel cannot be copied per thread without copying the
78 // model, so the builds take turns. Each grid point's factorization and
79 // likelihood still run concurrently.
80 std::mutex kernel_state;
81 auto builder = [this, &R_mod, &R_mod_ind, &kernel_state](double ls,
82 double noise_var)
83 -> std::tuple<EigenMatrix, EigenMatrix, Eigen::VectorXd> {
84 const std::lock_guard<std::mutex> lock(kernel_state);
85 sexpat_cov_func->setLengthScale(ls);
86 sigma2 = noise_var;
87
88 EigenMatrix K_train;
90
91 EigenMatrix K_train_query;
93 K_train_query);
94 // BMA expects (n_query x n_train); evaluateCovarianceMatrix
95 // returns (n_train x n_query). Transpose into the expected
96 // shape.
97 EigenMatrix K_cross = K_train_query.transpose();
98
99 EigenMatrix K_query_query;
100 evaluateTrainingCovarianceMatrix(R_mod, R_mod_ind, K_query_query);
101 Eigen::VectorXd k_diag = K_query_query.diagonal();
102 removeKernelNuggetFromDiagonal(R_mod, k_diag);
103
104 return {K_train, K_cross, k_diag};
105 };
106
107 Eigen::VectorXd y = energy_and_gradient;
108 if (y.size() == 0) return false;
109
110 bma.fit(y, builder);
111 pred_out = bma.predict(y, builder);
112
113 const Eigen::Index expected = static_cast<Eigen::Index>(N_im) * (D + 1);
114 if (pred_out.mean.size() != expected ||
115 pred_out.variance.size() != expected) {
116 return false;
117 }
118 return true;
119}
120
122{
123 BMAPrediction pred;
124 if (!runBMAGrid(image1, pred)) {
125 calculatePotential(image1);
126 return;
127 }
128 const Index_t N_im = static_cast<Index_t>(image1.R.rows());
129 const Index_t D = static_cast<Index_t>(image1.R.cols());
130 writeBMAOutput(pred.mean, N_im, D, image1);
131}
132
134{
135 BMAPrediction pred;
136 if (!runBMAGrid(image1, pred)) {
137 calculateMapVarianceInTrainingUnits(image1);
138 return;
139 }
140 const Index_t N_im = static_cast<Index_t>(image1.R.rows());
141 const Index_t D = static_cast<Index_t>(image1.R.cols());
142 // BMA-averaged variance includes both the within-model predictive
143 // variance and the between-model spread of the predictive means
144 // (law of total variance). Clip non-negative since round-off can
145 // produce small negatives near zero-uncertainty query points.
146 Eigen::VectorXd v = pred.variance.cwiseMax(0.0);
147 writeBMAOutput(v, N_im, D, image1);
148}
149
151GaussianProcessRegression::calculateBmaMixtureMeanHessianVector(
152 const Coord& R, const Eigen::VectorXd& direction,
153 Eigen::VectorXd& hessian_vector)
154{
155 hessian_vector.resize(0);
156 const Eigen::Index dof = R.cols();
157 if (uncertainty_mode_ != UncertaintyMode::BMA ||
158 atomic_environment_model_ || active_posterior_ ||
159 sexpat_cov_func == nullptr || R.rows() != 1 ||
160 direction.size() != dof || dof <= 0 || !R.allFinite() ||
161 !direction.allFinite() || R_matrix.size() == 0 ||
162 energy_and_gradient.size() == 0 || !energy_and_gradient.allFinite()) {
164 }
165
166 {
167 laplace::ScopedKernelState guard(*sexpat_cov_func, sigma2,
168 lik_gaussian.get());
169 const auto& ls_ref = sexpat_cov_func->getLengthScaleRef();
170 const double ls_star =
171 (ls_ref.size() > 0 && ls_ref(0, 0) > 0.0) ? ls_ref(0, 0) : 1.0;
172 const double sn2_star = (sigma2 > 0.0) ? sigma2 : 1e-6;
173 const double log_ls_min = std::log10(ls_star) - 1.0;
174 const double log_ls_max = std::log10(ls_star) + 1.0;
175 const double log_sn_min = std::log10(sn2_star) - 2.0;
176 const double log_sn_max = std::log10(sn2_star);
177 constexpr int n_ls = 5;
178 constexpr int n_noise = 5;
179 BayesianModelAveraging bma;
180 bma.setGrid(log_ls_min, log_ls_max, n_ls, log_sn_min, log_sn_max,
181 n_noise);
182
183 const Eigen::VectorXd y = energy_and_gradient;
184 // The fit calls this from an OpenMP loop; see runBMAGrid.
185 std::mutex kernel_state;
186 auto train_only = [this, &kernel_state](double ls, double noise_var)
187 -> std::tuple<EigenMatrix, EigenMatrix, Eigen::VectorXd> {
188 const std::lock_guard<std::mutex> lock(kernel_state);
189 sexpat_cov_func->setLengthScale(ls);
190 sigma2 = noise_var;
191 EigenMatrix K_train;
193 return {std::move(K_train), EigenMatrix(), Eigen::VectorXd()};
194 };
195 bma.fit(y, train_only);
196 const std::vector<double>& weights = bma.getWeights();
197 if (weights.size() != static_cast<std::size_t>(n_ls * n_noise))
199
200 const Eigen::VectorXd position = R.row(0).transpose();
201 Eigen::VectorXd sum = Eigen::VectorXd::Zero(dof);
202 bool visited = false;
203 std::size_t idx = 0;
204 for (int i = 0; i < n_ls; ++i) {
205 const double log_ls =
206 log_ls_min + (log_ls_max - log_ls_min) * i / (n_ls - 1);
207 for (int j = 0; j < n_noise; ++j, ++idx) {
208 if (weights[idx] < 1e-15) continue;
209 const double log_noise =
210 log_sn_min + (log_sn_max - log_sn_min) * j / (n_noise - 1);
211 const double ls = std::pow(10.0, log_ls);
212 const double noise_var = std::pow(10.0, log_noise);
213 sexpat_cov_func->setLengthScale(ls);
214 sigma2 = noise_var;
215 EigenMatrix K_XX;
217 if (K_XX.rows() != y.size() || K_XX.cols() != y.size() ||
218 !K_XX.allFinite()) {
220 }
221 K_XX.diagonal().array() += noise_var;
222 Eigen::LLT<EigenMatrix> llt(K_XX);
223 if (llt.info() != Eigen::Success)
225 const Eigen::VectorXd alpha = llt.solve(y);
226 Eigen::VectorXd action;
227 if (!alpha.allFinite() ||
228 !kernelMixtureComponentHessian(alpha, position, direction,
229 action)) {
231 }
232 sum.noalias() += weights[idx] * action;
233 visited = true;
234 }
235 }
236 if (visited) {
237 if (!finishMixtureMeanHessian(std::move(sum), R, direction,
238 hessian_vector))
241 }
242 }
243 // No component was visited, so calculatePotentialBMA uses the MAP
244 // mean. Contract that mean after the grid has restored the kernel.
245 return calculateMapFallbackMeanHessianVector(R, direction, hessian_vector);
246}
247
248} // namespace gpr
Full Bayesian posterior marginal GP/TP (FBPMGP).
@ y
Definition Enums.h:28
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.
void evaluateCovarianceMatrix(const EigenMatrix &x1, const EigenMatrix &x2, const Eigen::VectorXd &x1_ind, const Eigen::VectorXd &x2_ind, EigenMatrix &C, bool serial_per_rank=false) const
Evaluate covariance matrix between two input vectors.
void calculateVarianceBMA(Observation &image1)
Definition BMA.cpp:133
void calculatePotential(Observation &image1)
Calculate potential within GPR model.
Definition Predict.cpp:713
std::unique_ptr< SexpatCF > sexpat_cov_func
void calculatePotentialBMA(Observation &image1)
Definition BMA.cpp:121
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).
Gaussian-process regression, kernels, priors, and the searches that run on the surrogate.
Definition Macros.h:16
FieldMatrixd Coord
Definition Macros.h:35
uint32_t Index_t
Definition Macros.h:17
Eigen::Matrix< double, EigenDynamic, EigenDynamic, EigenMatrixStorage > EigenMatrix
Definition Macros.h:20
Prediction result from Bayesian model averaging.
Observation data: energy, gradient and positions.