Loading...
Searching...
No Matches
LaplaceINLA.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#include "LaplaceINLA.h"
6
7#include <algorithm>
8#include <cmath>
9#include <limits>
10#include <stdexcept>
11
15#ifdef USE_OPENMP
16#include <omp.h>
17#endif
18
19namespace gpr {
20
21namespace {
22
23// Rue et al. 2009 Sec 6.5 default radius in standardised space. For p = 2
24// gives f0 = 2, which is what test_ccd_grid_moments_p2 validates.
25double ruesDefaultF0(int p)
26{
27 return std::sqrt(static_cast<double>(p) + 2.0);
28}
29
30// The selected grid integrates z z^T to I. Each diagonal receives
31// 2 * Delta * f0^2 from the axes and n_corners * Delta * f0^2 / p
32// from the corners. An axial grid, including the one-dimensional rule
33// without duplicate corners, therefore has Delta = 1 / (2 * f0^2).
34double ruesDelta(int p, double f0, int n_corners)
35{
36 return 1.0 / (f0 * f0 * (2.0 + static_cast<double>(n_corners) / p));
37}
38
39} // namespace
40
41void LaplaceINLA::setTheta0(const Eigen::VectorXd& theta_star)
42{
43 theta_star_ = theta_star;
44 fitted_ = false;
45}
46
47void LaplaceINLA::setHessian(const Eigen::MatrixXd& H)
48{
49 setHessian(H, Eigen::MatrixXd{});
50}
51
52void LaplaceINLA::setHessian(const Eigen::MatrixXd& H,
53 const Eigen::MatrixXd& parameter_directions)
54{
55 if (H.rows() <= 0 || H.rows() != H.cols()) {
56 throw std::invalid_argument("LaplaceINLA::setHessian: H not square");
57 }
58 const bool constrained = parameter_directions.size() > 0;
59 const Eigen::Index ambient_dimension =
60 constrained ? parameter_directions.rows() : H.rows();
61 if (theta_star_.size() != 0 && ambient_dimension != theta_star_.size()) {
62 throw std::invalid_argument(
63 "LaplaceINLA::setHessian: H dimension does not match theta*");
64 }
65 Eigen::MatrixXd dual_directions;
66 if (constrained) {
67 if (parameter_directions.cols() != H.rows() ||
68 parameter_directions.rows() < parameter_directions.cols() ||
69 !parameter_directions.allFinite()) {
70 throw std::invalid_argument(
71 "LaplaceINLA::setHessian: invalid parameter directions");
72 }
73 const Eigen::MatrixXd gram =
74 parameter_directions.transpose() * parameter_directions;
75 Eigen::LLT<Eigen::MatrixXd> factor(gram);
76 if (factor.info() != Eigen::Success) {
77 throw std::invalid_argument(
78 "LaplaceINLA::setHessian: dependent parameter directions");
79 }
80 dual_directions =
81 factor.solve(parameter_directions.transpose()).transpose();
82 }
83 if (!H.allFinite()) {
84 throw std::runtime_error("LaplaceINLA::setHessian: H is not finite");
85 }
86 H_ = H;
87
88 // Eigendecompose the observed information. The posterior precision used
89 // for CCD must be proper even when weakly informed likelihood directions
90 // have mixed curvature, but a spectrum with no positive direction carries
91 // no local quadratic information to centre the approximation.
92 Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> solver(H_);
93 if (solver.info() != Eigen::Success) {
94 throw std::runtime_error("LaplaceINLA::setHessian: eigensolver failed");
95 }
96 lambda_ = solver.eigenvalues();
97 U_ = solver.eigenvectors();
98
99 const double lambda_max = lambda_.maxCoeff();
100 if (!lambda_.allFinite() || !(lambda_max > 0.0)) {
101 throw std::runtime_error(
102 "LaplaceINLA::setHessian: all eigenvalues of H are non-positive");
103 }
104
105 const double spectral_floor =
106 std::max(std::numeric_limits<double>::epsilon() * lambda_max,
107 std::numeric_limits<double>::min());
108 for (Eigen::Index i = 0; i < lambda_.size(); ++i) {
109 if (!(lambda_(i) > spectral_floor)) {
110 lambda_(i) = spectral_floor;
111 }
112 }
113
114 // Precision-form regularization, applied ONLY when needed. Rue,
115 // Martino, Chopin 2009; Martins, Simpson, Lindgren, Rue 2013
116 // "Bayesian computing with INLA: new features" Section 3.4.
117 //
118 // Weakly informed hyperparameters can give flat or mixed observed
119 // curvature. The eigenspace projection keeps positive observed
120 // directions, lifts non-positive directions by a backward-error-scale
121 // floor, and adds a Gaussian theta prior with precision
122 // tau * lambda_max * I:
123 // Q_eff = U max(Lambda, eps * lambda_max I) U^T
124 // + tau * lambda_max I
125 // Lambda_eff(i) = max(Lambda(i), eps * lambda_max)
126 // + tau * lambda_max
127 // so the CCD grid has finite axes and the local precision remains
128 // anchored to the observed spectral scale.
129 //
130 // Conditional application is critical: the bump shifts the
131 // eigenvalues uniformly, which moves moments. On well-conditioned
132 // H (cond < 1/kPrior) the bump is unnecessary and produces a
133 // (1 + tau)-factor on the unit-Gaussian moment recovery test.
134 // Skip when lambda_min/lambda_max >= kPrior so the no-flat-
135 // direction case stays bit-identical to the un-regularized form.
136 //
137 constexpr double kPrior = 1e-2;
138 const double prior_precision = kPrior * lambda_max;
139 const double lambda_min = lambda_.minCoeff();
140 const bool needs_regularization = (lambda_min < prior_precision);
141 if (needs_regularization) {
142 for (Eigen::Index i = 0; i < lambda_.size(); ++i) {
143 lambda_(i) += prior_precision;
144 }
145 }
146
147 // L_scale_ maps z-space to theta-space: theta = theta* + U
148 // Lambda_eff^{-1/2} z. Lambda_eff = Lambda + tau * lambda_max * I is
149 // well-conditioned by construction; cond(Lambda_eff) <= (lambda_max +
150 // prior) / prior = 1 + 1/tau = ~100 here, so the CCD grid is bounded.
151 L_scale_ = U_;
152 for (Eigen::Index i = 0; i < lambda_.size(); ++i) {
153 L_scale_.col(i) *= 1.0 / std::sqrt(lambda_(i));
154 }
155 if (constrained) {
156 L_scale_ = (parameter_directions * L_scale_).eval();
157 // Covariance lifts with J; its ambient precision lifts with the
158 // transpose of J's left inverse, so quadratic forms agree on J beta.
159 U_ = (dual_directions * U_).eval();
160 }
161
162 fitted_ = false;
163}
164
165void LaplaceINLA::buildGrid(double f0, bool include_corners)
166{
167 if (theta_star_.size() == 0) {
168 throw std::runtime_error("LaplaceINLA::buildGrid: setTheta0 first");
169 }
170 if (H_.size() == 0) {
171 throw std::runtime_error("LaplaceINLA::buildGrid: setHessian first");
172 }
173 const int p = static_cast<int>(L_scale_.cols());
174 if (f0 <= 0.0) f0 = ruesDefaultF0(p);
175 f0_ = f0;
176
177 z_k_.clear();
178 theta_k_.clear();
179
180 // 1 center.
181 z_k_.emplace_back(Eigen::VectorXd::Zero(p));
182
183 // 2p axial: +/- f0 e_i.
184 for (int i = 0; i < p; ++i) {
185 Eigen::VectorXd z_plus = Eigen::VectorXd::Zero(p);
186 Eigen::VectorXd z_minus = Eigen::VectorXd::Zero(p);
187 z_plus(i) = f0;
188 z_minus(i) = -f0;
189 z_k_.emplace_back(std::move(z_plus));
190 z_k_.emplace_back(std::move(z_minus));
191 }
192
193 // 2^p factorial corners at radius f0 in L2 (each axis at +/- f0/sqrt(p)).
194 // Skip when p == 1 because corner and axial points coincide (both at
195 // z = +/- f0) -- adding them would inflate the grid with duplicates.
196 // Skipped when include_corners == false to bound the per-call BMA /
197 // LAPLACE-CCD wall to the K = 1 + 2p axial subset.
198 // Both rules preserve the Gaussian mean and covariance; the corner
199 // points change the higher mixed moments of the quadrature.
200 if (include_corners && p >= 2) {
201 const int n_corner = 1 << p;
202 const double corner_axis = f0 / std::sqrt(static_cast<double>(p));
203 for (int bits = 0; bits < n_corner; ++bits) {
204 Eigen::VectorXd z(p);
205 for (int i = 0; i < p; ++i) {
206 const int sign = ((bits >> i) & 1) ? +1 : -1;
207 z(i) = sign * corner_axis;
208 }
209 z_k_.emplace_back(std::move(z));
210 }
211 }
212
213 // Map every z to theta = theta* + U Lambda^{-1/2} z.
214 theta_k_.reserve(z_k_.size());
215 for (const auto& z: z_k_) {
216 theta_k_.emplace_back(theta_star_ + L_scale_ * z);
217 }
218
219 // Grid quadrature weights: Delta on every non-center, w_0 on center.
220 const int n = static_cast<int>(z_k_.size());
221 const int n_corners = n - 1 - 2 * p;
222 const double delta = ruesDelta(p, f0, n_corners);
223 w_grid_ = Eigen::VectorXd::Constant(n, delta);
224 w_grid_(0) = 1.0 - static_cast<double>(n - 1) * delta;
225
226 fitted_ = false;
227}
228
229double LaplaceINLA::evaluateNLMLAtTheta(const Eigen::VectorXd& y,
230 KernelBuilder kb,
231 const Eigen::VectorXd& theta) const
232{
233 // Raw theta passes straight through to the builder; caller owns the
234 // log-base convention. Load-bearing contract (header-documented): the
235 // LAST element of theta is always log-noise (natural log), needed
236 // locally for FactorizedLikelihood::evaluateGP/evaluateTP's signal-
237 // to-noise term. Other components are opaque to LaplaceINLA.
238 if (theta.size() < 1) {
239 throw std::runtime_error(
240 "LaplaceINLA::evaluateNLMLAtTheta: theta must have at least one "
241 "component (log-noise)");
242 }
243 auto [K_XX, K_cross, k_diag] = kb(theta);
244 (void)K_cross;
245 (void)k_diag;
246
247 // Inner Laplace path: opt-in, requires an attached ObservationLikelihood.
248 // K_XX here is the PRIOR covariance on the latent f (no noise added);
249 // findFMode + laplaceMarginalLogLik handle the rest.
250 if (lik_ == Likelihood::NON_GAUSSIAN) {
251 if (!ol_) {
252 throw std::runtime_error(
253 "LaplaceINLA: NON_GAUSSIAN requested but no "
254 "ObservationLikelihood attached (setObservationLikelihood)");
255 }
256 const Eigen::VectorXd f_mode = findFMode(K_XX, y, *ol_);
257 return -laplaceMarginalLogLik(K_XX, y, f_mode, *ol_);
258 }
259
260 Eigen::SelfAdjointEigenSolver<EigenMatrix> solver(K_XX);
261 const Eigen::VectorXd D = solver.eigenvalues();
262 const EigenMatrix U = solver.eigenvectors();
263
264 FactorizedLikelihood fl;
265 fl.setEigendecomposition(D, U, y);
266
267 const double noise = std::exp(theta(theta.size() - 1));
268
269 // FactorizedLikelihood returns log p(y|theta); phi wants -log p(y|theta)
270 // so we negate. BMA does the same (see BayesianModelAveraging.cpp:78-79).
271 if (lik_ == Likelihood::T_CLOSED_FORM) {
272 return -fl.evaluateTP(noise, tp_a_, tp_b_);
273 }
274 return -fl.evaluateGP(noise);
275}
276
277void LaplaceINLA::fit(const Eigen::VectorXd& y, KernelBuilder kb,
278 LogPrior log_prior)
279{
280 if (theta_k_.empty()) {
281 throw std::runtime_error("LaplaceINLA::fit: buildGrid first");
282 }
283 const int n = static_cast<int>(theta_k_.size());
284 const double phi_star =
285 evaluateNLMLAtTheta(y, kb, theta_star_) - log_prior(theta_star_);
286
287 // Compute delta_phi_k in parallel: each grid point is an independent
288 // NLML evaluation + log-prior call (same cost model as BMA's fit loop).
289 std::vector<double> delta_phi(n);
290#ifdef USE_OPENMP
291#pragma omp parallel for schedule(dynamic)
292#endif
293 for (int k = 0; k < n; ++k) {
294 const Eigen::VectorXd& theta_k = theta_k_[k];
295 const Eigen::VectorXd d = theta_k - theta_star_;
296 const double quad = 0.5 * d.dot(precisionMatrix() * d);
297 const double phi_k =
298 evaluateNLMLAtTheta(y, kb, theta_k) - log_prior(theta_k);
299 delta_phi[k] = phi_k - phi_star - quad;
300 }
301
302 // rho_k := exp(-delta_phi_k). Subtract the minimum for numerical
303 // stability before the exp (same log-sum-exp trick BMA uses).
304 const double dmin = *std::min_element(delta_phi.begin(), delta_phi.end());
305 Eigen::VectorXd rho(n);
306 for (int k = 0; k < n; ++k) {
307 rho(k) = std::exp(-(delta_phi[k] - dmin));
308 }
309
310 // Final posterior weights: w_k = w_k^grid * rho_k / Z.
311 w_final_.resize(n);
312 double Z = 0.0;
313 for (int k = 0; k < n; ++k) {
314 w_final_(k) = w_grid_(k) * rho(k);
315 Z += w_final_(k);
316 }
317 if (!(Z > 0.0)) {
318 throw std::runtime_error(
319 "LaplaceINLA::fit: all grid weights collapsed to 0");
320 }
321 w_final_ /= Z;
322 fitted_ = true;
323}
324
325INLAPrediction LaplaceINLA::predict(const Eigen::VectorXd& y,
326 KernelBuilder kb) const
327{
328 linalg::BackendContext workspace;
329 return predict(y, std::move(kb), workspace);
330}
331
333 linalg::BackendContext& workspace) const
334{
335 if (!fitted_) {
336 throw std::runtime_error("LaplaceINLA::predict: fit first");
337 }
338
340 out.n_grid_points = static_cast<int>(theta_k_.size());
341 bool first = true;
342 Eigen::VectorXd weighted_mean;
343 Eigen::VectorXd weighted_sq; // E[mu^2 + var] under the mixture
344 // Dropping negligible components renormalises the mixture, so the law of
345 // total variance below is applied to weights that no longer sum to one.
346 // Track the retained mass and divide it back out.
347 double retained_weight = 0.0;
348
349 for (size_t k = 0; k < theta_k_.size(); ++k) {
350 if (w_final_(k) < 1e-15) continue;
351 retained_weight += w_final_(k);
352 const Eigen::VectorXd& theta_k = theta_k_[k];
353 auto [K_XX, K_cross, k_diag] = kb(theta_k);
354 // Contract: last element of theta is always log-noise (natural log).
355 const double noise = std::exp(theta_k(theta_k.size() - 1));
356
357 K_XX.diagonal().array() += noise;
358 EigenMatrix L;
359 if (!workspace.cholesky(K_XX, L)) {
360 throw std::runtime_error(
361 "LaplaceINLA::predict: covariance is not positive definite");
362 }
363 Eigen::VectorXd alpha =
364 workspace.back_solve(L, workspace.forward_solve(L, y));
365 Eigen::VectorXd mu = K_cross * alpha;
366 EigenMatrix V = workspace.back_solve_mat(
367 L, workspace.forward_solve_mat(L, K_cross.transpose()));
368 Eigen::VectorXd var =
369 k_diag -
370 (K_cross.array() * V.transpose().array()).rowwise().sum().matrix();
371 var = var.cwiseMax(0.0);
372
373 if (first) {
374 weighted_mean = w_final_(k) * mu;
375 weighted_sq = w_final_(k) * (var + mu.array().square().matrix());
376 first = false;
377 } else {
378 weighted_mean += w_final_(k) * mu;
379 weighted_sq += w_final_(k) * (var + mu.array().square().matrix());
380 }
381 }
382
383 if (first || !(retained_weight > 0.0)) {
384 // Every component fell below the inclusion threshold, so there is no
385 // posterior to report. Returning the default-constructed empty vectors
386 // would look like a valid zero-length prediction.
387 throw std::runtime_error(
388 "LaplaceINLA::predict: every mixture component has negligible "
389 "weight");
390 }
391
392 weighted_mean /= retained_weight;
393 weighted_sq /= retained_weight;
394
395 out.mean = weighted_mean;
396 // Law of total variance: Var = E[var] + Var[mu] = weighted_sq - mean^2.
397 out.variance = weighted_sq - weighted_mean.array().square().matrix();
398 out.variance = out.variance.cwiseMax(0.0);
399 return out;
400}
401
402} // namespace gpr
@ z
Definition Enums.h:28
@ y
Definition Enums.h:28
Eigendecomposition-based log marginal likelihood evaluation.
INLA-style Laplace approximation of the GP/TP hyperparameter posterior.
Non-Gaussian observation-likelihood scaffolding for INLA inner Laplace.
@ NON_GAUSSIAN
Inner Laplace via ObservationLikelihood (future).
Definition LaplaceINLA.h:80
@ T_CLOSED_FORM
FactorizedLikelihood::evaluateTP (MVT marginal).
Definition LaplaceINLA.h:79
INLAPrediction predict(const Eigen::VectorXd &y, KernelBuilder kernel_builder) const
Predictive moments at the test points embedded in the kernel builder's K_test_X / k_test_test outputs...
void fit(const Eigen::VectorXd &y, KernelBuilder kernel_builder, LogPrior log_prior)
Evaluate the per-grid-point correction rho_k = exp(-Delta phi_k) and build the final normalised weigh...
int p() const noexcept
void setHessian(const Eigen::MatrixXd &H)
Eigen::MatrixXd precisionMatrix() const
std::function< double(const Eigen::VectorXd &theta)> LogPrior
Definition LaplaceINLA.h:93
void setTheta0(const Eigen::VectorXd &theta_star)
MAP hyperparameters (log space if using the project's conventions).
std::function< std::tuple< EigenMatrix, EigenMatrix, Eigen::VectorXd >( const Eigen::VectorXd &theta)> KernelBuilder
Definition LaplaceINLA.h:87
void buildGrid(double f0=-1.0, bool include_corners=true)
Build the CCD grid in theta-space from (theta*, H).
Eigen::VectorXd forward_solve(const EigenMatrix &L, const Eigen::VectorXd &b)
EigenMatrix back_solve_mat(const EigenMatrix &L, const EigenMatrix &B)
EigenMatrix forward_solve_mat(const EigenMatrix &L, const EigenMatrix &B)
bool cholesky(const EigenMatrix &C, EigenMatrix &L)
Eigen::VectorXd back_solve(const EigenMatrix &L, const Eigen::VectorXd &b)
eon_relax_band_t eon_relax_surface_fn void eon_relax_outcome_t * out
Gaussian-process regression, kernels, priors, and the searches that run on the surrogate.
Definition Macros.h:16
Eigen::VectorXd findFMode(const EigenMatrix &K, const Eigen::VectorXd &y, const ObservationLikelihood &ol, int max_iter, double tol)
Posterior mode f_mode = argmax_f [log p(y|f) + log N(f | 0, K)] via the Rasmussen-Williams safe Newto...
double laplaceMarginalLogLik(const EigenMatrix &K, const Eigen::VectorXd &y, const Eigen::VectorXd &f_mode, const ObservationLikelihood &ol)
Laplace approximation to log p(y | theta) given prior K and the converged posterior mode f_mode (R&W ...
Eigen::Matrix< double, EigenDynamic, EigenDynamic, EigenMatrixStorage > EigenMatrix
Definition Macros.h:20