Loading...
Searching...
No Matches
Helpers.h
Go to the documentation of this file.
1// SPDX-License-Identifier: MIT
2// Copyright (c) gpridge developers
3// See LICENSE for details.
4#pragma once
5
6// TU-private leaf helpers shared across the GP module .cpp split.
7// All functions are inline so the header can be included from multiple
8// translation units without ODR violations. None of these helpers cache
9// state or own resources; each takes its inputs as const references and
10// returns by value.
11
12#include <Eigen/Core>
13#include <algorithm>
14#include <cmath>
15#include <cstddef>
16#include <cstdlib>
17#include <limits>
18#include <stdexcept>
19#include <string>
20#include <vector>
21
26
27#ifdef GPR_LINALG_SCALAPACK
30#endif
31
32namespace gpr::detail {
33
34inline ScgCurvatureMode parseScgCurvatureMode(const std::string& value)
35{
36 if (value == "exact") return ScgCurvatureMode::EXACT;
37 if (value == "finite_difference")
39 if (value == "nlml_hessian_vector")
41 throw std::invalid_argument("Unknown SCG curvature_mode: " + value);
42}
43
44inline double localTraceProduct(const EigenMatrix& A, const EigenMatrix& B)
45{
46 if (A.rows() != B.rows() || A.cols() != B.cols()) {
47 return std::numeric_limits<double>::quiet_NaN();
48 }
49 double sum = 0.0;
50 const Eigen::Index size = A.size();
51 const double* a = A.data();
52 const double* b = B.data();
53 for (Eigen::Index i = 0; i < size; ++i)
54 sum += a[i] * b[i];
55 return sum;
56}
57
58inline Eigen::Index leadingDerivativeBlockSize(const Eigen::VectorXd& indices,
59 const double block_value)
60{
61 Eigen::Index count = 0;
62 while (count < indices.size() && indices(count) == block_value)
63 ++count;
64 return count;
65}
66
67inline void addConstantCovarianceBlock(ConstantCF* const_cov_fun,
68 const Eigen::VectorXd& row_indices,
69 const Eigen::VectorXd& col_indices,
70 EigenMatrix& matrix)
71{
72 if (const_cov_fun == nullptr || matrix.size() == 0) return;
73 const double const_sigma2 = const_cov_fun->getConstSigma2();
74 if (const_sigma2 == 0.0) return;
75
76 const Eigen::Index row_block = leadingDerivativeBlockSize(row_indices, 0.0);
77 const Eigen::Index col_block = leadingDerivativeBlockSize(col_indices, 0.0);
78 if (row_block <= 0 || col_block <= 0 || row_block > matrix.rows() ||
79 col_block > matrix.cols()) {
80 return;
81 }
82 matrix.topLeftCorner(row_block, col_block).array() += const_sigma2;
83}
84
85inline Eigen::VectorXd constantCovarianceUpdate(ConstantCF* constant,
86 const Eigen::VectorXd& indices)
87{
88 Eigen::VectorXd update = Eigen::VectorXd::Zero(indices.size());
89 if (constant != nullptr) {
90 const double amplitude = std::sqrt(constant->getConstSigma2());
91 for (Eigen::Index row = 0; row < indices.size(); ++row)
92 if (indices(row) == 0.0) update(row) = amplitude;
93 }
94 return update;
95}
96
97inline void addSeparatedConstantNugget(ConstantCF* constant,
98 const Eigen::VectorXd& indices,
99 const double eta, EigenMatrix& matrix)
100{
101 if (constant == nullptr || eta == 0.0) return;
102 const Eigen::Index count = leadingDerivativeBlockSize(indices, 0.0);
103 matrix.diagonal().head(count).array() += eta * constant->getConstSigma2();
104}
105
106inline bool symmetrizeObservedInformation(Eigen::MatrixXd& H)
107{
108 if (H.rows() == 0 || H.rows() != H.cols() || !H.allFinite()) {
109 return false;
110 }
111 H = (0.5 * (H + H.transpose())).eval();
112 return H.allFinite();
113}
114
115// When the triangles disagree, replace the matrix by 0.5*(C+C^T) and
116// factor that copy. The product is evaluated first: assigning the
117// expression over the same matrix reads entries that the write has
118// already replaced. A symmetric matrix is factored as stored. No jitter.
119// A symmetric part that will not factor fails, and a symmetric input
120// stays unchanged.
121template <typename Factor>
122inline bool factorCovarianceOrSymmetricPart(EigenMatrix& covariance,
123 Factor&& factor)
124{
125 if (covariance.rows() != covariance.cols() || !covariance.allFinite())
126 return false;
127 if ((covariance - covariance.transpose()).lpNorm<Eigen::Infinity>() > 0.0) {
128 covariance = (0.5 * (covariance + covariance.transpose())).eval();
129 if (!covariance.allFinite()) return false;
130 }
131 return static_cast<bool>(factor(covariance));
132}
133
134inline Eigen::VectorXd inlaClipToLogBox(const Eigen::VectorXd& theta,
135 const Eigen::VectorXd& lower,
136 const Eigen::VectorXd& upper)
137{
138 Eigen::VectorXd clipped = theta;
139 for (Eigen::Index i = 0; i < clipped.size(); ++i) {
140 clipped(i) = std::min(upper(i), std::max(lower(i), clipped(i)));
141 }
142 return clipped;
143}
144
145inline void appendScalarColumn(FieldMatrixd& row, const double value)
146{
147 if (row.size() == 0) {
148 row.resize(1, 1);
149 row(0, 0) = value;
150 return;
151 }
152 const Eigen::Index old_cols = row.cols();
153 row.conservativeResize(1, old_cols + 1);
154 row(0, old_cols) = value;
155}
156
157inline Eigen::Vector3d priorParametersVector(const PriorBase& prior)
158{
159 Eigen::Vector3d out;
160 out << prior.getMu(), prior.getS2(), prior.getNu();
161 return out;
162}
163
164inline void writePredictionVectorToObservation(const Observation& query,
165 const Eigen::VectorXd& values,
167{
168 const Index_t n = query.R.rows();
169 const Index_t D = query.R.cols();
170 out = query;
171 out.E.resize(1, n);
172 out.E = Eigen::Map<const Eigen::RowVectorXd>(values.data(), n);
173 out.G.resize(n, D);
174 out.G = Eigen::Map<const Eigen::Matrix<double, Eigen::Dynamic,
175 Eigen::Dynamic, Eigen::ColMajor>>(
176 values.data() + n, n, D);
177}
178
179// In-place variant used by the BMA and PSIS predict paths: image1 is
180// the destination for a flattened (N_im * (D + 1)) prediction vector.
181// Differs from writePredictionVectorToObservation in that it does not
182// reset image1 from a separate query (the caller already has the query
183// shape on image1).
184inline void writeBMAOutput(const Eigen::VectorXd& flat, Index_t N_im, Index_t D,
185 Observation& image1)
186{
187 image1.E.resize(1, N_im);
188 image1.E = Eigen::Map<const Eigen::RowVectorXd>(flat.data(), N_im);
189 image1.G.resize(N_im, D);
190 image1.G = Eigen::Map<const Eigen::Matrix<double, Eigen::Dynamic,
191 Eigen::Dynamic, Eigen::ColMajor>>(
192 flat.data() + N_im, N_im, D);
193}
194
195template <typename EigenObject>
196inline bool reduce_laplace_factor_vectors_in_grid_order(
197 std::vector<EigenObject>& factor_values, linalg::BackendContext& context)
198{
199 if (factor_values.empty()) return true;
200
201 const Eigen::Index n_values = factor_values.front().size();
202 for (const auto& values: factor_values) {
203 if (values.size() != n_values) return false;
204 }
205 const Eigen::Index n_factors =
206 static_cast<Eigen::Index>(factor_values.size());
207 const Eigen::Index n_total = n_values * n_factors;
208 if (n_total > std::numeric_limits<int>::max()) return false;
209
210#ifdef GPR_LINALG_SCALAPACK
211 if (context.mpi().nprocs > 1 && n_total > 0) {
212 std::vector<double> buffer(static_cast<std::size_t>(n_total), 0.0);
213 for (Eigen::Index k = 0; k < n_factors; ++k) {
214 std::copy_n(factor_values[static_cast<std::size_t>(k)].data(),
215 static_cast<std::size_t>(n_values),
216 buffer.data() + static_cast<std::size_t>(k * n_values));
217 }
218
219 context.ordered_sum_bcast(buffer.data(), static_cast<int>(n_total));
220
221 for (Eigen::Index k = 0; k < n_factors; ++k) {
222 std::copy_n(buffer.data() + static_cast<std::size_t>(k * n_values),
223 static_cast<std::size_t>(n_values),
224 factor_values[static_cast<std::size_t>(k)].data());
225 }
226 }
227#endif
228
229 return true;
230}
231
232// --- Marchildon & Zingg principled nugget (arXiv:2307.05855, GpGradPy) ---
233//
234// Bounds cond(K_tilde + eta I) <= kappa_max for the (gradient-enhanced)
235// kernel via a DATA-DRIVEN nugget, with no tuned scale. K_tilde =
236// P^{-1} K P^{-1}, P = sqrt(diag(K)) is the symmetric Jacobi preconditioner
237// that turns K into a unit-diagonal correlation matrix.
238
239// Numerical-stability ceiling for cond(K_tilde + eta I). An SPD Cholesky
240// solve has relative error ~ eps * cond; capping cond at 1/sqrt(eps)
241// ~ 6.7e7 keeps the relative solve error near sqrt(eps) ~ 1.5e-8, i.e. it
242// preserves half of the 16 double-precision digits. This is a stability
243// BOUND derived from machine epsilon, not a tuned length/scale parameter.
245{
246 return 1.0 / std::sqrt(std::numeric_limits<double>::epsilon());
247}
248
249// eta = n_x (d+1) / (kappa_max - 1) for the gradient-enhanced kernel
250// (matrix dimension N = n_x (d+1)); eta = n_x / (kappa_max - 1) gradient-
251// free. After symmetric Jacobi preconditioning K_tilde has unit diagonal,
252// so trace(K_tilde) = N and lambda_max(K_tilde) <= N; adding eta I gives
253// cond <= (N + eta) / eta = 1 + N/eta, and eta = N/(kappa_max - 1) makes
254// this <= kappa_max.
255inline double computePrincipledNugget(Eigen::Index n_x, Eigen::Index d,
256 double kappa_max,
257 bool gradient_enhanced = true)
258{
259 if (!(kappa_max > 1.0) || n_x <= 0) return 0.0;
260 const double N = gradient_enhanced
261 ? static_cast<double>(n_x) * static_cast<double>(d + 1)
262 : static_cast<double>(n_x);
263 return N / (kappa_max - 1.0);
264}
265
266// Symmetric Jacobi preconditioner P = sqrt(diag(K)); returns the unit-
267// diagonal correlation matrix K_tilde = P^{-1} K P^{-1} and P. Used for the
268// condition-number diagnostic and the proof. The production solve uses the
269// algebraically folded form below.
270inline bool symmetricJacobiPrecondition(const EigenMatrix& K,
271 EigenMatrix& K_tilde,
272 Eigen::VectorXd& P)
273{
274 if (K.rows() != K.cols() || K.rows() == 0) return false;
275 const Eigen::Index n = K.rows();
276 P.resize(n);
277 for (Eigen::Index i = 0; i < n; ++i) {
278 const double dd = K(i, i);
279 if (!(dd > 0.0)) return false;
280 P(i) = std::sqrt(dd);
281 }
282 const Eigen::VectorXd inv = P.cwiseInverse();
283 K_tilde = inv.asDiagonal() * K * inv.asDiagonal();
284 return true;
285}
286
287// Apply the principled nugget in place, folding the preconditioner back
288// onto the original kernel:
289// K_tilde + eta I = P^{-1} (K + eta P^2) P^{-1}, P^2 = diag(K),
290// so K(i,i) += eta * K(i,i) regularizes K such that its symmetric Jacobi
291// preconditioning is exactly K_tilde + eta I. Cholesky is invariant under
292// symmetric diagonal scaling (chol(D A D) = D chol(A), van der Sluis 1969),
293// so the folded factor inherits the kappa_max-bounded backward stability,
294// and the standard solve alpha = (K + eta diag(K))^{-1} y is already the
295// un-preconditioned mean weight (the P factors cancel). Returns eta.
296inline double applyPrincipledDiagonalNugget(EigenMatrix& K, Eigen::Index n_x,
297 Eigen::Index d, double kappa_max,
298 bool gradient_enhanced = true)
299{
300 if (K.rows() != K.cols() || K.rows() == 0) return 0.0;
301 const double eta =
302 computePrincipledNugget(n_x, d, kappa_max, gradient_enhanced);
303 if (!(eta > 0.0)) return 0.0;
304 for (Eigen::Index i = 0; i < K.rows(); ++i)
305 K(i, i) += eta * K(i, i);
306 return eta;
307}
308
309} // namespace gpr::detail
Linear algebra abstraction layer for GPR hot-path operations.
Constant covariance function.
Definition ConstantCF.h:21
double getConstSigma2()
Class of prior parameters.
Definition PriorBase.h:23
double getMu() const
Definition PriorBase.h:48
double getS2() const
Definition PriorBase.h:53
double getNu() const
Definition PriorBase.h:58
eon_relax_band_t eon_relax_surface_fn void eon_relax_outcome_t * out
ScgCurvatureMode
Selects how SCG computes the directional curvature term.
Definition Structures.h:161
double principledKappaMaxDefault()
Definition Helpers.h:244
uint32_t Index_t
Definition Macros.h:17
Eigen::Matrix< double, EigenDynamic, EigenDynamic, EigenMatrixStorage > EigenMatrix
Definition Macros.h:20
Eigen::Matrix< double, EigenDynamic, EigenDynamic, FieldMatrixStorage > FieldMatrixd
Definition Macros.h:25
Observation data: energy, gradient and positions.
FieldMatrixd E