Loading...
Searching...
No Matches
TCovSecondOrder.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// Analytical 2nd-order trainable-covariance Laplace correction (partial scope).
6//
7// The A1-A8 identities proved in
8// python/tests/test_sympy_laplace_tcov_analytical.py
9// give closed forms for dK/dtheta and d^2K/dtheta_i dtheta_j on the complete
10// joint energy-gradient training kernel. The directional covariance API
11// assembles every EE, EG, GE, and GG block in the training and query layouts.
12//
13// Under A2, in the partial scope:
14// K_{0, 0} = dK / d log_magn (so K_{ij} = K_i when j = 0)
15// K_{0, d} = dK / d log_ls_d (so K_{ij} = K_d when i = 0, j = d > 0)
16// and the same identities hold on the train-vs-query cross-covariance by
17// A4 (log-space chain rule on the gradient block). Therefore the cache
18// only needs K_d for d = 0 (log_magn) and d = 1..n_ls (log_ls_d). The
19// log_sn dim is not touched: A2 gives all (log_sn, *) pairs = 0 in the
20// partial scope (and exactly 0 on cross-cov by A3).
21//
22// Implementation:
23// compute() -> (n_ls + 1) calls to gpr.assembleDirectional-
24// CovarianceDerivatives(e_d) to build full K_d on
25// the training block, then one Cholesky-solve per
26// d for z_d and (n_ls + 1) more for beta_{0, d}.
27// applyCorrection -> builds the same (n_ls + 1) full cross-cov
28// derivative matrices between training rows and
29// query-mod rows (R_mod from image1.R) by calling
30// the SexpatCF directional API block-by-block in
31// the same layout as applyCrossCovarianceFunction.
32// Then per-query inner products assemble the
33// scalar d^2 mu / d theta_i d theta_j (x*).
34
35#include "TCovSecondOrder.h"
36
37#include <Eigen/Dense>
38#include <cstddef>
39#include <vector>
40
47
48namespace gpr {
49namespace laplace {
50
51// Build a full cross-cov derivative matrix for the SexpatCF only along a
52// unit direction e_d (d in 0..n_ls). Mirrors the block layout of
53// GaussianProcessRegression::applyCrossCovarianceFunction but substitutes
54// the directional API for the kernel evaluators. The const-cov-fun
55// contribution is identically zero (ConstantCF::calculateGradOfCov* all
56// return empty / zero -- see gpr/covariance_functions/ConstantCF.cpp).
57//
58// @param gpr GPR carrying R_matrix, R_indices, sexpat_cov_func.
59// @param x_q Query coordinate matrix (R_mod rows).
60// @param q_ind Query indices (R_mod_ind).
61// @param dir Direction vector (1 + n_ls)-dim passed to the SexpatCF
62// directional API; noise dim not included.
63// @param K_out [out] matrix of shape (R_matrix.rows(), x_q.rows())
64// containing `first = dK/d theta` along direction.
65// Compute BOTH the first and second directional derivatives of the
66// cross-covariance K(R_matrix, x_q) along a theta-direction `dir`.
67// Passing nullptr for either output skips the assembly of that order.
68//
69// The SexpatCF directional API returns first + second in one shot on
70// each block, so extracting both is free. Having the 2nd directional
71// derivative at the cross-cov lets the Laplace mixture use the
72// polarisation identity
73// d^2 K / d theta_i d theta_j = 0.5 * (d^2 K/d(e_i+e_j)^2 - d^2 K/de_i^2 -
74// d^2 K/de_j^2)
75// without a new SexpatCF method.
76void TCovSecondOrder::assembleCrossCovDirectional(
77 const GaussianProcessRegression& gpr, const Eigen::MatrixXd& x_q,
78 const Eigen::VectorXd& q_ind, const Eigen::VectorXd& dir,
79 Eigen::MatrixXd* K_first_out, Eigen::MatrixXd* K_second_out)
80{
81 const EigenMatrix& x1 = gpr.getRMatrix();
82 const Eigen::VectorXd& ind1 = gpr.getRIndices();
83 SexpatCF& cov = *gpr.sexpat_cov_func;
84
85 Eigen::VectorXd uDdim1, uDdim2;
86 gpr.extractUniqueIndices(ind1, uDdim1);
87 gpr.extractUniqueIndices(q_ind, uDdim2);
88
89 if (K_first_out) *K_first_out = EigenMatrix::Zero(x1.rows(), x_q.rows());
90 if (K_second_out) *K_second_out = EigenMatrix::Zero(x1.rows(), x_q.rows());
91
92 Eigen::Map<const Eigen::ArrayXd> ind1_arr(ind1.data(), ind1.size());
93 Eigen::Map<const Eigen::ArrayXd> ind2_arr(q_ind.data(), q_ind.size());
94
95 FieldMatrixd x1_loc_0, x2_loc_0, x1_loc_1, x2_loc_1;
96 FieldMatrixd block_first, block_second;
97 FieldMatrixIdx dims1(1, 1), dims2(1, 1);
98
99 const Eigen::Index cnt1_0 = (ind1_arr == 0).count();
100 const Eigen::Index cnt2_0 = (ind2_arr == 0).count();
101
102 x1_loc_0.resize(cnt1_0, x1.cols() + 1);
103 x1_loc_0.setZero();
104 x2_loc_0.resize(cnt2_0, x_q.cols() + 1);
105 x2_loc_0.setZero();
106
107 gpr.extractCoordinatesByIndex(x1, ind1, 0, x1_loc_0);
108 gpr.extractCoordinatesByIndex(x_q, q_ind, 0, x2_loc_0);
109
110 // Block (0, 0): energy train x energy query.
111 if (cnt1_0 > 0 && cnt2_0 > 0) {
112 cov.calculateDirectionalCovarianceMatrix(x1_loc_0, x2_loc_0, dir,
113 block_first, block_second);
114 if (K_first_out && block_first.size() != 0) {
115 gpr.assignBlockToMatrix(ind1, q_ind, 0, 0, block_first,
116 *K_first_out);
117 }
118 if (K_second_out && block_second.size() != 0) {
119 gpr.assignBlockToMatrix(ind1, q_ind, 0, 0, block_second,
120 *K_second_out);
121 }
122 }
123
124 // Block (0, j): energy train x gradient-j query. Use ginput4 analog:
125 // calculateDirectionalCovarianceMatrixWithDerivatives(x_q_1, x1_loc_0,
126 // dims2) returns dK/d theta of k(d_j(x_q), x1_loc_0); assign transposed.
127 if (cnt1_0 > 0) {
128 for (Eigen::Index i = 0; i < uDdim2.size(); ++i) {
129 dims2(0, 0) = static_cast<Index_t>(uDdim2[i]);
130 const Eigen::Index cnt2_j = (ind2_arr == uDdim2[i]).count();
131 x2_loc_1.resize(cnt2_j, x_q.cols() + 1);
132 x2_loc_1.setZero();
133 gpr.extractCoordinatesByIndex(
134 x_q, q_ind, static_cast<Index_t>(uDdim2[i]), x2_loc_1);
135 cov.calculateDirectionalCovarianceMatrixWithDerivatives(
136 x2_loc_1, x1_loc_0, dims2, dir, block_first, block_second);
137 if (K_first_out && block_first.size() != 0) {
138 gpr.assignBlockToMatrix(ind1, q_ind, 0,
139 static_cast<Index_t>(uDdim2[i]),
140 block_first, *K_first_out,
141 /*transpose_field=*/true);
142 }
143 if (K_second_out && block_second.size() != 0) {
144 gpr.assignBlockToMatrix(ind1, q_ind, 0,
145 static_cast<Index_t>(uDdim2[i]),
146 block_second, *K_second_out,
147 /*transpose_field=*/true);
148 }
149 }
150 }
151
152 // Block (i, 0): gradient-i train x energy query.
153 if (cnt2_0 > 0) {
154 for (Eigen::Index i = 0; i < uDdim1.size(); ++i) {
155 dims1(0, 0) = static_cast<Index_t>(uDdim1[i]);
156 const Eigen::Index cnt1_i = (ind1_arr == uDdim1[i]).count();
157 x1_loc_1.resize(cnt1_i, x1.cols() + 1);
158 x1_loc_1.setZero();
159 gpr.extractCoordinatesByIndex(
160 x1, ind1, static_cast<Index_t>(uDdim1[i]), x1_loc_1);
161 cov.calculateDirectionalCovarianceMatrixWithDerivatives(
162 x1_loc_1, x2_loc_0, dims1, dir, block_first, block_second);
163 if (K_first_out && block_first.size() != 0) {
164 gpr.assignBlockToMatrix(ind1, q_ind,
165 static_cast<Index_t>(uDdim1[i]), 0,
166 block_first, *K_first_out);
167 }
168 if (K_second_out && block_second.size() != 0) {
169 gpr.assignBlockToMatrix(ind1, q_ind,
170 static_cast<Index_t>(uDdim1[i]), 0,
171 block_second, *K_second_out);
172 }
173 }
174 }
175
176 // Block (i, j): gradient-i train x gradient-j query.
177 for (Eigen::Index i = 0; i < uDdim1.size(); ++i) {
178 dims1(0, 0) = static_cast<Index_t>(uDdim1[i]);
179 const Eigen::Index cnt1_i = (ind1_arr == uDdim1[i]).count();
180 x1_loc_1.resize(cnt1_i, x1.cols() + 1);
181 x1_loc_1.setZero();
182 gpr.extractCoordinatesByIndex(x1, ind1, static_cast<Index_t>(uDdim1[i]),
183 x1_loc_1);
184 for (Eigen::Index j = 0; j < uDdim2.size(); ++j) {
185 dims2(0, 0) = static_cast<Index_t>(uDdim2[j]);
186 const Eigen::Index cnt2_j = (ind2_arr == uDdim2[j]).count();
187 x2_loc_1.resize(cnt2_j, x_q.cols() + 1);
188 x2_loc_1.setZero();
189 gpr.extractCoordinatesByIndex(
190 x_q, q_ind, static_cast<Index_t>(uDdim2[j]), x2_loc_1);
191 cov.calculateDirectionalCovarianceMatrixWithDerivatives2(
192 x1_loc_1, x2_loc_1, dims1, dims2, dir, block_first,
193 block_second);
194 if (K_first_out && block_first.size() != 0) {
195 gpr.assignBlockToMatrix(
196 ind1, q_ind, static_cast<Index_t>(uDdim1[i]),
197 static_cast<Index_t>(uDdim2[j]), block_first, *K_first_out);
198 }
199 if (K_second_out && block_second.size() != 0) {
200 gpr.assignBlockToMatrix(ind1, q_ind,
201 static_cast<Index_t>(uDdim1[i]),
202 static_cast<Index_t>(uDdim2[j]),
203 block_second, *K_second_out);
204 }
205 }
206 }
207}
208
210 const Eigen::MatrixXd& H_inv)
211{
212 invalidate();
213
214 if (gpr.sexpat_cov_func == nullptr) return false;
215 if (gpr.getRMatrix().size() == 0) return false;
216 if (gpr.getAlpha().size() == 0) return false;
217 // The triangular solves below consult the ScaLAPACK factor cache when
218 // the dense L member is empty, so require a USABLE factor rather than
219 // dense dimensions (hasTrainingCholeskyFactor covers both states).
220 if (!gpr.hasTrainingCholeskyFactor(gpr.getRMatrix().rows())) return false;
221
222 // Partial scope: log_sn is not touched (A2 gives all (log_sn, *) pairs
223 // zero, A3 gives cross-cov log_sn derivs zero). We only need K_d for
224 // d in {0 (log_magn), 1..n_ls (log_ls)}.
225 const auto& ls_ref = gpr.sexpat_cov_func->getLengthScaleRef();
226 const Eigen::Index n_ls = ls_ref.size();
227 if (n_ls < 1) return false;
228
229 // SexpatCF directional API guards on lengthScale.size() <= 1 with an
230 // empty-matrix early return. Without a working directional API on
231 // single-pair-type systems, the cache cannot be populated -- refuse
232 // and let the caller fall back to MAP. Production atomistic systems
233 // (d016, CuH2 multi-pairtype) have n_ls > 1.
234 if (n_ls <= 1) return false;
235
236 n_ls_ = static_cast<std::size_t>(n_ls);
237 const int p = static_cast<int>(H_inv.rows());
238 const int p_expected = 1 + static_cast<int>(n_ls) + 1; // magn + ls + sn
239 if (p != p_expected) return false;
240 if (H_inv.cols() != p) return false;
241
242 H_inv_ = H_inv;
243 alpha_star_ = gpr.getAlpha();
244
245 Eigen::VectorXd uDdim;
246 gpr.extractUniqueIndices(gpr.getRIndices(), uDdim);
247
248 // Build K_d (1st directional) AND K_{dd} (2nd directional) for
249 // d = 0..n_ls in a single directional pass along e_d in the
250 // (1 + n_ls)-dim SexpatCF direction space. The noise dim is not
251 // part of the SexpatCF direction vector.
252 const Eigen::Index p_sex = 1 + n_ls;
253 K_d_.clear();
254 K_d_.reserve(n_ls_ + 1);
255 std::vector<EigenMatrix> K_dd_diag; // K_{dd} = d^2 K / d theta_d^2
256 K_dd_diag.reserve(n_ls_ + 1);
257 EigenMatrix first, second;
258 for (Eigen::Index d = 0; d <= n_ls; ++d) {
259 Eigen::VectorXd e_d = Eigen::VectorXd::Zero(p_sex);
260 e_d(d) = 1.0;
261 first.resize(0, 0);
262 second.resize(0, 0);
263 gpr.assembleDirectionalCovarianceDerivatives(
264 gpr.getRMatrix(), gpr.getRIndices(), uDdim, e_d, first, second);
265 if (first.size() == 0 || second.size() == 0) {
266 invalidate();
267 return false;
268 }
269 first = gpr.symmetricMatrixInTrainingFactorLayout(first);
270 second = gpr.symmetricMatrixInTrainingFactorLayout(second);
271 K_d_.push_back(std::move(first));
272 K_dd_diag.push_back(std::move(second));
273 }
274
275 // Build off-diagonal K_{ij} = d^2 K / d theta_i d theta_j for i < j
276 // via polarisation (A7 identity):
277 // K_{ij} = 0.5 * (d^2 K/d(e_i+e_j)^2 - K_{ii} - K_{jj})
278 // The sum-direction (e_i + e_j) needs one directional probe per
279 // pair. p(p+1)/2 - p = n_ls * (n_ls + 1) / 2 mixed pairs.
280 // We index K_ij_full_ flat: entry (i, j) with i <= j lives at
281 // index ij_flat_index(i, j).
282 const std::size_t p_eff = n_ls_ + 1; // number of d dims with non-zero K_d
283 K_ij_full_.clear();
284 K_ij_full_.resize(p_eff * (p_eff + 1) / 2);
285
286 // Fill diagonal slots (i == i) with K_{ii} from the probes above.
287 for (std::size_t i = 0; i < p_eff; ++i) {
288 K_ij_full_[ijFlatIndex(i, i)] = std::move(K_dd_diag[i]);
289 }
290
291 // Fill off-diagonal pairs via polarisation. `second` is reused.
292 for (Eigen::Index i = 0; i < static_cast<Eigen::Index>(p_eff); ++i) {
293 for (Eigen::Index j = i + 1; j < static_cast<Eigen::Index>(p_eff);
294 ++j) {
295 Eigen::VectorXd sum_dir = Eigen::VectorXd::Zero(p_sex);
296 sum_dir(i) = 1.0;
297 sum_dir(j) = 1.0;
298 first.resize(0, 0);
299 second.resize(0, 0);
300 gpr.assembleDirectionalCovarianceDerivatives(
301 gpr.getRMatrix(), gpr.getRIndices(), uDdim, sum_dir, first,
302 second);
303 if (second.size() == 0) {
304 invalidate();
305 return false;
306 }
307 second = gpr.symmetricMatrixInTrainingFactorLayout(second);
308 // K_{ij} = 0.5 * (second - K_{ii} - K_{jj})
309 EigenMatrix Kij =
310 0.5 * (second -
311 K_ij_full_[ijFlatIndex(static_cast<std::size_t>(i),
312 static_cast<std::size_t>(i))] -
313 K_ij_full_[ijFlatIndex(static_cast<std::size_t>(j),
314 static_cast<std::size_t>(j))]);
315 K_ij_full_[ijFlatIndex(static_cast<std::size_t>(i),
316 static_cast<std::size_t>(j))] =
317 std::move(Kij);
318 }
319 }
320
321 // z_d = K^{-1} K_d alpha_star for d = 0..n_ls.
322 z_.clear();
323 z_.reserve(p_eff);
324 for (std::size_t d = 0; d < p_eff; ++d) {
325 const Eigen::VectorXd Kd_alpha = K_d_[d] * alpha_star_;
326 z_.push_back(gpr.solveTrainingCovarianceInFactorLayout(Kd_alpha));
327 }
328
329 // beta_{ij} = K^{-1} (K_i z_j + K_j z_i - K_{ij} alpha_star) for
330 // each i <= j. Symmetric, so we only store upper-triangular (i<=j).
331 beta_full_.clear();
332 beta_full_.resize(p_eff * (p_eff + 1) / 2);
333 for (std::size_t i = 0; i < p_eff; ++i) {
334 for (std::size_t j = i; j < p_eff; ++j) {
335 const auto& K_ij = K_ij_full_[ijFlatIndex(i, j)];
336 Eigen::VectorXd rhs;
337 if (i == j) {
338 rhs = 2.0 * (K_d_[i] * z_[i]) - K_ij * alpha_star_;
339 } else {
340 rhs = K_d_[i] * z_[j] + K_d_[j] * z_[i] - K_ij * alpha_star_;
341 }
342 beta_full_[ijFlatIndex(i, j)] =
343 gpr.solveTrainingCovarianceInFactorLayout(rhs);
344 }
345 }
346
347 // Keep the partial-scope beta_ for callers that read it; populate
348 // beta_[0..n_ls] as (0, d) pairs per its API contract.
349 beta_.clear();
350 beta_.reserve(p_eff);
351 for (std::size_t d = 0; d < p_eff; ++d) {
352 beta_.push_back(beta_full_[ijFlatIndex(0, d)]);
353 }
354
355 valid_ = true;
356 return true;
357}
358
360 Observation& image1)
361{
362 if (!valid_) return;
363 if (gpr.sexpat_cov_func == nullptr) return;
364 if (gpr.getRMatrix().size() == 0) return;
365
366 const Index_t N_im = static_cast<Index_t>(image1.R.rows());
367 const Index_t D = static_cast<Index_t>(image1.R.cols());
368 if (N_im == 0) return;
369
370 // Build R_mod + R_mod_ind from image1.R using the same stacked layout
371 // that calculatePotential uses. Row layout:
372 // [R_im (energy block, 0..N_im-1),
373 // R_im (d=1 block, N_im..2*N_im-1),
374 // ...,
375 // R_im (d=D block, D*N_im..(D+1)*N_im-1)]
376 // Column 0 of K_out will contain the energy prediction coefficients,
377 // cols N_im..2*N_im-1 the d=1 gradient coefficients, etc.
378 EigenMatrix R_mod;
379 Eigen::VectorXd R_mod_ind;
381 aux_func.assembleMatrixOfRepetitiveCoordinates(image1.R, R_mod, R_mod_ind);
382
383 const Eigen::Index n_ls = static_cast<Eigen::Index>(n_ls_);
384 const Eigen::Index p_sex = 1 + n_ls;
385 const Eigen::Index m_q = R_mod.rows();
386
387 // Build cross-cov k_star(x*, X) between training and query (the
388 // full sexpat+const kernel; same as calculatePotential's KK without
389 // permutation). We reuse evaluateCovarianceMatrix for this.
390 EigenMatrix k_star;
391 gpr.evaluateCovarianceMatrix(gpr.getRMatrix(), R_mod, gpr.getRIndices(),
392 R_mod_ind, k_star);
393 k_star = gpr.rowsInTrainingFactorLayout(k_star);
394
395 // Build directional cross-cov derivatives at the query for each
396 // theta_d and for the sum-directions (e_i + e_j) needed by the
397 // polarisation identity. One directional probe per d returns BOTH
398 // first and second derivatives; the second output is the diagonal
399 // d^2 k / d theta_d^2 (x*, X). The sum-direction probes then supply
400 // the off-diagonal pairs via 0.5 * (d^2 k/d(e_i+e_j)^2 - k_{ii} - k_{jj}).
401 const std::size_t p_eff = n_ls_ + 1;
402 std::vector<EigenMatrix> dk_cross(p_eff); // k_d (first)
403 std::vector<EigenMatrix> dk2_cross(p_eff * (p_eff + 1) / 2); // k_{ij}
404 for (Eigen::Index d = 0; d <= n_ls; ++d) {
405 Eigen::VectorXd e_d = Eigen::VectorXd::Zero(p_sex);
406 e_d(d) = 1.0;
407 const std::size_t du = static_cast<std::size_t>(d);
408 EigenMatrix diag_second;
409 TCovSecondOrder::assembleCrossCovDirectional(
410 gpr, R_mod, R_mod_ind, e_d, &dk_cross[du], &diag_second);
411 dk_cross[du] = gpr.rowsInTrainingFactorLayout(dk_cross[du]);
412 diag_second = gpr.rowsInTrainingFactorLayout(diag_second);
413 dk2_cross[ijFlatIndex(du, du)] = std::move(diag_second);
414 }
415 for (Eigen::Index i = 0; i <= n_ls; ++i) {
416 for (Eigen::Index j = i + 1; j <= n_ls; ++j) {
417 Eigen::VectorXd sum_dir = Eigen::VectorXd::Zero(p_sex);
418 sum_dir(i) = 1.0;
419 sum_dir(j) = 1.0;
420 EigenMatrix sum_second;
421 TCovSecondOrder::assembleCrossCovDirectional(
422 gpr, R_mod, R_mod_ind, sum_dir, nullptr, &sum_second);
423 sum_second = gpr.rowsInTrainingFactorLayout(sum_second);
424 // k_{ij} = 0.5 * (sum_second - k_{ii} - k_{jj})
425 const auto& k_ii = dk2_cross[ijFlatIndex(
426 static_cast<std::size_t>(i), static_cast<std::size_t>(i))];
427 const auto& k_jj = dk2_cross[ijFlatIndex(
428 static_cast<std::size_t>(j), static_cast<std::size_t>(j))];
429 dk2_cross[ijFlatIndex(static_cast<std::size_t>(i),
430 static_cast<std::size_t>(j))] =
431 0.5 * (sum_second - k_ii - k_jj);
432 }
433 }
434
435 // Full quadratic-form accumulation with H_inv over all (i, j) pairs
436 // i, j in {0..n_ls}. For i == j the coefficient is 0.5 * H_inv(i,i);
437 // for i != j, the symmetric pair (i,j) + (j,i) contributes
438 // 2 * 0.5 * H_inv(i,j) = H_inv(i,j). Noise dim is omitted (A3 proves
439 // all cross-cov log_sn derivatives are zero).
440 Eigen::VectorXd corr = Eigen::VectorXd::Zero(m_q);
441
442 // Pre-compute the m_q-length inner-product row vectors for each d:
443 // z_dot_k[d][e][q] = z_[e]^T * dk_cross[d].col(q)
444 std::vector<std::vector<Eigen::RowVectorXd>> z_dot_k(p_eff);
445 for (std::size_t d = 0; d < p_eff; ++d) {
446 z_dot_k[d].resize(p_eff);
447 for (std::size_t e = 0; e < p_eff; ++e) {
448 z_dot_k[d][e] = z_[e].transpose() * dk_cross[d];
449 }
450 }
451 // k_star^T * beta_{ij}: row vector per upper-triangular pair
452 std::vector<Eigen::RowVectorXd> kstar_dot_beta(p_eff * (p_eff + 1) / 2);
453 for (std::size_t i = 0; i < p_eff; ++i) {
454 for (std::size_t j = i; j < p_eff; ++j) {
455 kstar_dot_beta[ijFlatIndex(i, j)] =
456 beta_full_[ijFlatIndex(i, j)].transpose() * k_star;
457 }
458 }
459
460 // Accumulate d^2 mu / d theta_i d theta_j contributions.
461 // d^2 mu / d theta_i d theta_j (x*) =
462 // k_{ij}(x*)^T alpha_star
463 // - k_i(x*)^T z_j - k_j(x*)^T z_i
464 // + k_star(x*)^T beta_{ij}
465 // corr[q] = sum_{i<=j} coeff_{ij} * d2mu_{ij}(x*[q])
466 // where coeff_{ii} = 0.5 * H_inv(i,i) and coeff_{ij}_{i<j} = H_inv(i,j).
467 for (std::size_t i = 0; i < p_eff; ++i) {
468 for (std::size_t j = i; j < p_eff; ++j) {
469 const Eigen::Index ii = static_cast<Eigen::Index>(i);
470 const Eigen::Index jj = static_cast<Eigen::Index>(j);
471 Eigen::RowVectorXd kij_dot_a =
472 alpha_star_.transpose() * dk2_cross[ijFlatIndex(i, j)];
473 Eigen::RowVectorXd d2_ij = kij_dot_a - z_dot_k[i][j] -
474 z_dot_k[j][i] +
475 kstar_dot_beta[ijFlatIndex(i, j)];
476 const double coeff =
477 (i == j) ? 0.5 * H_inv_(ii, jj) : H_inv_(ii, jj);
478 corr += coeff * d2_ij.transpose();
479 }
480 }
481
482 // Trust-region cap on the Taylor correction (TR2 in
483 // python/tests/test_sympy_laplace_trust_region.py): if the
484 // correction exceeds tau * |MAP|, fall back to bare MAP for that
485 // component. tau < 1 guarantees the corrected gradient stays in
486 // the same hemisphere as MAP -- so dimer acquisition decisions
487 // don't flip sign even with the (capped) Bayesian correction.
488 // Conn-Gould-Toint 2000 trust-region technique applied to the
489 // Bayesian Taylor expansion. No-op in the well-conditioned
490 // regime (PET-MAD-scale, TR3); active in the small-data regime
491 // (CuH2-scale, TR4).
492 auto cap = [](double map_val, double corr_val) {
493 // Quiet NaN must not reach fabs. Caller also skips this when the
494 // MAP energy is non-finite and has already zeroed the gradient.
495 if (!std::isfinite(map_val) || !std::isfinite(corr_val)) return 0.0;
496 const double bound = TCovSecondOrder::kTrustTau * std::fabs(map_val);
497 if (std::fabs(corr_val) <= bound) return corr_val;
498 return std::copysign(bound, corr_val);
499 };
500 // corr is m_q = N_im * (D + 1) entries: first N_im are energy, next
501 // N_im are gradient-dim-1, ..., last N_im are gradient-dim-D. Add
502 // element-wise to image1.E (RowVector, size N_im) and image1.G
503 // (N_im x D), with per-component trust-region cap.
504 for (Index_t i = 0; i < N_im; ++i) {
505 if (!std::isfinite(image1.E(0, i))) {
506 image1.G.row(i).setZero();
507 continue;
508 }
509 image1.E(0, i) += cap(image1.E(0, i), corr(i));
510 }
511 for (Index_t d = 0; d < D; ++d) {
512 for (Index_t i = 0; i < N_im; ++i) {
513 if (!std::isfinite(image1.E(0, i))) continue;
514 const double component = image1.G(i, d);
515 if (!std::isfinite(component)) {
516 image1.G(i, d) = 0.0;
517 continue;
518 }
519 const double c =
520 corr(static_cast<Eigen::Index>((d + 1) * N_im + i));
521 image1.G(i, d) += cap(component, c);
522 }
523 }
524}
525
526} // namespace laplace
527} // namespace gpr
Linear algebra abstraction layer for GPR hot-path operations.
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 invalidate() noexcept
Invalidate (drops all cached vectors).
bool compute(const GaussianProcessRegression &gpr, const Eigen::MatrixXd &H_inv)
static constexpr double kTrustTau
void applyCorrection(const GaussianProcessRegression &gpr, Observation &image1)
Gaussian-process regression, kernels, priors, and the searches that run on the surrogate.
Definition Macros.h:16
Eigen::Matrix< Index_t, EigenDynamic, EigenDynamic, FieldMatrixStorage > FieldMatrixIdx
Definition Macros.h:29
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