Loading...
Searching...
No Matches
SmoothedCurvatureSpectrum.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#include <Eigen/Cholesky>
7#include <Eigen/Eigenvalues>
8#include <Eigen/QR>
9#include <algorithm>
10#include <array>
11#include <cmath>
12#include <limits>
13#include <optional>
14#include <random>
15#include <utility>
16#include <vector>
17
20
21namespace gpr::optim {
22
29 Eigen::VectorXd direction;
30 Eigen::VectorXd action;
31 Eigen::VectorXd variance;
32 bool refined = false;
33};
34
53 bool valid = false;
55 Eigen::Index local_samples = 0;
60 Eigen::VectorXd curvatures;
61 Eigen::VectorXd mean_curvatures;
62 Eigen::MatrixXd modes;
63 Eigen::VectorXd spreads;
67 Eigen::VectorXd measured_spreads;
68 Eigen::VectorXd floors;
69 Eigen::MatrixXd hessian;
70 Eigen::MatrixXd measured_span;
77 double prior_absolute_variance = std::numeric_limits<double>::quiet_NaN();
78 double prior_relative_variance = std::numeric_limits<double>::quiet_NaN();
79 double prior_coupling_variance = std::numeric_limits<double>::quiet_NaN();
80 double stencil_inflation = std::numeric_limits<double>::quiet_NaN();
81};
82
83namespace detail {
84
88inline Eigen::HouseholderQR<Eigen::MatrixXd> latentGaussianFactor(
89 const Eigen::MatrixXd& design)
90{
91 Eigen::MatrixXd augmented(design.rows() + design.cols(), design.cols());
92 augmented.topRows(design.rows()) = design;
93 augmented.bottomRows(design.cols()).setIdentity();
94 return Eigen::HouseholderQR<Eigen::MatrixXd>(augmented);
95}
96
97struct LatentGaussianEvidence {
98 Eigen::VectorXd mean;
99 double log_determinant = std::numeric_limits<double>::quiet_NaN();
100 bool gram_factor = false;
101};
102
107inline LatentGaussianEvidence latentGaussianEvidence(
108 const Eigen::MatrixXd& design, const Eigen::VectorXd& observation)
109{
110 LatentGaussianEvidence out;
111 const double eps = std::numeric_limits<double>::epsilon();
112 const double operations =
113 static_cast<double>(design.rows() + design.cols() + 1);
114 const double rounding = operations * eps;
115 const double gram_error =
116 rounding / (1.0 - rounding) * (1.0 + design.squaredNorm());
117 if (rounding < 1.0 && gram_error <= std::sqrt(eps)) {
118 Eigen::MatrixXd precision =
119 Eigen::MatrixXd::Identity(design.cols(), design.cols());
120 precision.selfadjointView<Eigen::Lower>().rankUpdate(
121 design.transpose());
122 const Eigen::LLT<Eigen::MatrixXd> factor(precision);
123 if (factor.info() == Eigen::Success) {
124 out.mean = factor.solve(design.transpose() * observation);
125 out.log_determinant =
126 2.0 * factor.matrixLLT().diagonal().array().log().sum();
127 if (out.mean.allFinite() && std::isfinite(out.log_determinant)) {
128 out.gram_factor = true;
129 return out;
130 }
131 }
132 }
133 const auto factor = latentGaussianFactor(design);
134 Eigen::VectorXd rhs = Eigen::VectorXd::Zero(design.rows() + design.cols());
135 rhs.head(design.rows()) = observation;
136 out.mean = factor.solve(rhs);
137 out.log_determinant = 2.0 * factor.matrixQR()
138 .topRows(design.cols())
139 .diagonal()
140 .cwiseAbs()
141 .array()
142 .log()
143 .sum();
144 return out;
145}
146
150struct ConditionedEntryErrors {
151 bool valid = false;
152 Eigen::VectorXd mean;
153 Eigen::VectorXd independent_deviation;
154 Eigen::MatrixXd correlated_factor;
155};
156
161inline ConditionedEntryErrors conditionEntryErrors(
162 const Eigen::MatrixXd& loading, const Eigen::VectorXd& coupling_variance,
163 const Eigen::VectorXd& precision, const Eigen::VectorXd& weighted_residual)
164{
165 ConditionedEntryErrors out;
166 const Eigen::ArrayXd attenuation =
167 (1.0 + coupling_variance.array() * precision.array()).inverse();
168 const Eigen::VectorXd independent_variance =
169 coupling_variance.array() * attenuation;
170 const Eigen::MatrixXd attenuated =
171 attenuation.matrix().asDiagonal() * loading;
172 const Eigen::VectorXd observation_scale =
173 (precision.array() * attenuation).sqrt();
174 const Eigen::MatrixXd design = observation_scale.asDiagonal() * loading;
175 const auto factor = latentGaussianFactor(design);
176 Eigen::VectorXd rhs =
177 Eigen::VectorXd::Zero(loading.rows() + loading.cols());
178 for (Eigen::Index i = 0; i < loading.rows(); ++i)
179 if (precision(i) > 0.0)
180 rhs(i) =
181 observation_scale(i) * (weighted_residual(i) / precision(i));
182 out.mean = independent_variance.cwiseProduct(weighted_residual);
183 out.mean.noalias() += attenuated * factor.solve(rhs);
184 out.independent_deviation = independent_variance.array().sqrt();
185 const Eigen::MatrixXd upper = factor.matrixQR()
186 .topRows(loading.cols())
187 .triangularView<Eigen::Upper>();
188 out.correlated_factor = upper.transpose()
189 .triangularView<Eigen::Lower>()
190 .solve(attenuated.transpose())
191 .transpose();
192 // For A = [S B; I] = Q R, the observed rows obey B_i R^-1 = Q_i / S_i.
193 // Strong observations use this identity to avoid cancellation in the
194 // triangular solve at nearly exact precision. Weak observations retain
195 // the solve so division by a small observation scale cannot amplify
196 // the absolute rounding error in Q.
197 if ((design.rowwise().squaredNorm().array() >= 1.0).any()) {
198 const Eigen::MatrixXd orthogonal =
199 factor.householderQ() *
200 Eigen::MatrixXd::Identity(design.rows() + design.cols(),
201 design.cols());
202 for (Eigen::Index i = 0; i < loading.rows(); ++i)
203 if (design.row(i).squaredNorm() >= 1.0)
204 out.correlated_factor.row(i) =
205 (attenuation(i) / observation_scale(i)) * orthogonal.row(i);
206 }
207 out.valid = out.mean.allFinite() && out.independent_deviation.allFinite() &&
208 out.correlated_factor.allFinite();
209 return out;
210}
211
215inline constexpr Eigen::Index kSpectrumSamples = 128;
216
220struct StructuredEntryMarginal {
221 Eigen::MatrixXd loading;
222 Eigen::VectorXd lambda_squared;
223 Eigen::VectorXd coupling;
224 Eigen::VectorXd noise;
225 Eigen::VectorXd residual;
226 double log_likelihood_offset = 0.0;
227 double reference_noise_logdet_offset = 0.0;
228
234 StructuredEntryMarginal atFixedCoupling(double variance) const
235 {
236 const Eigen::VectorXd diagonal = noise + variance * coupling;
237 const Eigen::VectorXd scale = diagonal.array().sqrt().inverse();
238 const Eigen::MatrixXd whitened = scale.asDiagonal() * loading;
239 const Eigen::HouseholderQR<Eigen::MatrixXd> qr(whitened);
240 const Eigen::VectorXd rotated =
241 qr.householderQ().adjoint() * scale.cwiseProduct(residual);
242 const Eigen::Index width = std::min(loading.rows(), loading.cols());
243 StructuredEntryMarginal reduced;
244 reduced.loading =
245 qr.matrixQR().topRows(width).triangularView<Eigen::Upper>();
246 reduced.lambda_squared = lambda_squared;
247 reduced.coupling = Eigen::VectorXd::Zero(width);
248 reduced.noise = Eigen::VectorXd::Ones(width);
249 reduced.residual = rotated.head(width);
250 double logdet = 0.0;
251 for (Eigen::Index i = 0; i < diagonal.size(); ++i) {
252 const double ratio = variance * coupling(i) / noise(i);
253 logdet += std::isfinite(ratio)
254 ? std::log1p(ratio)
255 : std::log(diagonal(i)) - std::log(noise(i));
256 }
257 reduced.log_likelihood_offset =
258 log_likelihood_offset -
259 0.5 * (logdet + rotated.tail(rotated.size() - width).squaredNorm());
260 reduced.reference_noise_logdet_offset =
261 reference_noise_logdet_offset + noise.array().log().sum();
262 return reduced;
263 }
264
267 double normalizedLogLikelihood(const std::vector<double>& variances) const
268 {
269 const double refused = -std::numeric_limits<double>::infinity();
270 const Eigen::VectorXd diagonal = noise + variances[2] * coupling;
271 if (!(diagonal.array() > 0.0).all() || !diagonal.allFinite())
272 return refused;
273 const Eigen::VectorXd deviation =
274 (variances[0] + variances[1] * lambda_squared.array()).sqrt();
275 const Eigen::VectorXd inverse_deviation =
276 diagonal.array().sqrt().inverse();
277 const Eigen::MatrixXd whitened =
278 inverse_deviation.asDiagonal() * loading * deviation.asDiagonal();
279 const Eigen::VectorXd y = inverse_deviation.cwiseProduct(residual);
280 const auto latent = latentGaussianEvidence(whitened, y);
281 if (!latent.mean.allFinite() || !std::isfinite(latent.log_determinant))
282 return refused;
283 // The residual and latent prior norms equal r^T C^-1 r without
284 // subtracting two large quadratic forms for precise observations.
285 const double quadratic = (y - whitened * latent.mean).squaredNorm() +
286 latent.mean.squaredNorm();
287 double logdet = latent.log_determinant;
288 for (Eigen::Index i = 0; i < diagonal.size(); ++i) {
289 const double ratio = variances[2] * coupling(i) / noise(i);
290 logdet += std::isfinite(ratio)
291 ? std::log1p(ratio)
292 : std::log(diagonal(i)) - std::log(noise(i));
293 }
294 const double value = log_likelihood_offset - 0.5 * (logdet + quadratic);
295 return std::isfinite(value) ? value : refused;
296 }
297
298 double operator()(const std::vector<double>& variances) const
299 {
300 return normalizedLogLikelihood(variances) -
301 0.5 *
302 (noise.array().log().sum() + reference_noise_logdet_offset);
303 }
304};
305
316inline void maximizeEntryMarginal(
317 const std::vector<std::vector<double>>& coefficients,
318 const std::vector<double>& residual_sq, const std::vector<double>& noise,
319 std::vector<double>& variances, const std::vector<double>& warm_start = {},
320 const StructuredEntryMarginal* joint = nullptr)
321{
322 const std::size_t parameters = coefficients.size();
323 const std::size_t entries = residual_sq.size();
324 variances.assign(parameters, 0.0);
325 const auto total_variance = [&](std::size_t k) {
326 double total = noise[k];
327 for (std::size_t p = 0; p < parameters; ++p)
328 total += coefficients[p][k] * variances[p];
329 return total;
330 };
331 const auto objective = [&](const StructuredEntryMarginal* reduced =
332 nullptr) {
333 if (reduced != nullptr)
334 return reduced->normalizedLogLikelihood(variances);
335 if (joint != nullptr) return joint->normalizedLogLikelihood(variances);
336 double total = 0.0;
337 for (std::size_t k = 0; k < entries; ++k) {
338 const double variance = total_variance(k);
339 const double ratio = variance / noise[k];
340 const double log_ratio =
341 std::isfinite(ratio) ? std::log(ratio)
342 : std::log(variance) - std::log(noise[k]);
343 total -= 0.5 * (log_ratio + residual_sq[k] / variance);
344 }
345 return total;
346 };
347 const double eps = std::numeric_limits<double>::epsilon();
348 const double golden = 0.5 * (std::sqrt(5.0) - 1.0);
349 const auto line = [&](std::size_t p) {
350 // The coupling fixes the whitening throughout either eigenvalue
351 // variance line search. Factor that tall matrix once for this line.
352 std::optional<StructuredEntryMarginal> reduced;
353 if (joint != nullptr && p < 2 &&
354 joint->loading.rows() > joint->loading.cols())
355 reduced = joint->atFixedCoupling(variances[2]);
356 const auto line_objective = [&]() {
357 return objective(reduced ? &*reduced : nullptr);
358 };
359 double upper = 0.0;
360 const double held = variances[p];
361 const double at_held = line_objective();
362 variances[p] = 0.0;
363 // An entry this variance barely reaches (a coefficient at the
364 // roundoff of the largest) does not set the bracket: it would
365 // ask for an astronomical variance to explain its residual, which
366 // the entries the variance does reach then rule out.
367 double largest = 0.0;
368 for (std::size_t k = 0; k < entries; ++k)
369 largest = std::max(largest, coefficients[p][k]);
370 const double reach = std::sqrt(eps) * largest;
371 for (std::size_t k = 0; k < entries; ++k)
372 if (coefficients[p][k] > reach)
373 upper = std::max(upper, (residual_sq[k] - total_variance(k)) /
374 coefficients[p][k]);
375 const auto f = [&](double x) {
376 variances[p] = x;
377 return line_objective();
378 };
379 if (joint != nullptr) upper = std::max(upper, held);
380 if (!(upper > 0.0)) {
381 const double at_zero = line_objective();
382 variances[p] = at_zero > at_held ? 0.0 : held;
383 return at_zero > at_held;
384 }
385 if (joint != nullptr) {
386 // The marginal bracket supplies a scale. Correlations change
387 // its bound, so extend it while the joint evidence rises.
388 double high_value = f(upper);
389 while (upper < std::numeric_limits<double>::max() / 2.0) {
390 const double expanded = f(2.0 * upper);
391 if (!(expanded > high_value)) break;
392 upper *= 2.0;
393 high_value = expanded;
394 }
395 }
396 // Search a dimensionless fraction of the bracket. Adding log(upper)
397 // to every coordinate would carry the curvature units into rounding.
398 double lo = std::log(eps), hi = 0.0;
399 double x1 = hi - golden * (hi - lo), x2 = lo + golden * (hi - lo);
400 double f1 = f(upper * std::exp(x1)), f2 = f(upper * std::exp(x2));
401 while (hi - lo > std::sqrt(eps)) {
402 if (f1 < f2) {
403 lo = x1;
404 x1 = x2;
405 f1 = f2;
406 x2 = lo + golden * (hi - lo);
407 f2 = f(upper * std::exp(x2));
408 } else {
409 hi = x2;
410 x2 = x1;
411 f2 = f1;
412 x1 = hi - golden * (hi - lo);
413 f1 = f(upper * std::exp(x1));
414 }
415 }
416 const double best = upper * std::exp(0.5 * (lo + hi));
417 const double at_best = f(best);
418 const double at_zero = f(0.0);
419 variances[p] = at_held >= std::max(at_best, at_zero)
420 ? held
421 : (at_best >= at_zero ? best : 0.0);
422 return std::max(at_best, at_zero) > at_held;
423 };
424 // Coordinate ascent from each single-variance start, the best end
425 // point kept: starting from one variance alone avoids the ridge where
426 // a variance that barely reaches an entry explains it at an enormous
427 // value before the variance that does reach it is tried. A warm start
428 // (the previous fit of a growing column set) replaces the starts.
429 std::vector<double> best;
430 double best_value = -std::numeric_limits<double>::infinity();
431 std::vector<std::vector<double>> starts;
432 if (warm_start.size() == parameters &&
433 std::all_of(warm_start.begin(), warm_start.end(),
434 [](double v) { return std::isfinite(v) && v >= 0.0; })) {
435 starts.push_back(warm_start);
436 } else {
437 for (std::size_t start = 0; start < parameters; ++start) {
438 std::vector<double> one(parameters, 0.0);
439 one[start] = -1.0; // marker: the line search sets it
440 starts.push_back(one);
441 }
442 }
443 for (const auto& start: starts) {
444 variances = start;
445 for (std::size_t p = 0; p < parameters; ++p)
446 if (variances[p] < 0.0) {
447 variances[p] = 0.0;
448 line(p);
449 }
450 // A variance has units of curvature squared. Stopping on its
451 // absolute change makes the fit depend on the chosen units.
452 // Every accepted coordinate strictly improves the same objective;
453 // a sweep without such an improvement exhausts this ascent.
454 for (;;) {
455 bool moved = false;
456 for (std::size_t coordinate = 0; coordinate < parameters;
457 ++coordinate) {
458 // Coupling errors admit measured rotations of the
459 // eigenbasis before eigenvalue errors adjust their scale.
460 const std::size_t p =
461 joint != nullptr
462 ? (coordinate + parameters - 1) % parameters
463 : coordinate;
464 moved = line(p) || moved;
465 }
466 if (!moved) break;
467 }
468 const double value = objective();
469 if (best.empty() || value > best_value) {
470 best = variances;
471 best_value = value;
472 }
473 }
474 variances = best;
475}
476
477} // namespace detail
478
479namespace detail {
480
481struct PreparedCurvatureSpectrum {
482 bool valid = false;
483 SmoothedCurvatureSpectrum spectrum;
484 Eigen::MatrixXd mean;
485 Eigen::VectorXd precision;
486 ConditionedEntryErrors posterior;
487 ConditionedEntryErrors floor_posterior;
488};
489
494inline PreparedCurvatureSpectrum prepareSmoothedCurvature(
495 const Eigen::MatrixXd& prior,
496 const std::vector<MeasuredHessianColumn>& columns,
497 const SmoothedCurvatureSpectrum* previous = nullptr)
498{
499 PreparedCurvatureSpectrum prepared;
500 auto& out = prepared.spectrum;
501 const Eigen::Index d = prior.rows();
502 if (d == 0 || prior.cols() != d || !prior.allFinite() || columns.empty())
503 return prepared;
504 const Eigen::Index m = static_cast<Eigen::Index>(columns.size());
505 if (m > d) return prepared;
506 Eigen::MatrixXd directions(d, m), actions(d, m), variances(d, m);
507 for (Eigen::Index j = 0; j < m; ++j) {
508 const auto& column = columns[static_cast<std::size_t>(j)];
509 if (column.direction.size() != d || column.action.size() != d ||
510 column.variance.size() != d || !column.direction.allFinite() ||
511 !column.action.allFinite() || !column.variance.allFinite() ||
512 !(column.variance.array() > 0.0).all())
513 return prepared;
514 directions.col(j) = column.direction;
515 actions.col(j) = column.action;
516 variances.col(j) = column.variance;
517 }
518 const double tolerance = std::sqrt(std::numeric_limits<double>::epsilon() *
519 static_cast<double>(d));
520 if ((directions.transpose() * directions - Eigen::MatrixXd::Identity(m, m))
521 .norm() > tolerance)
522 return prepared;
523 // Orthonormal basis with the measured directions leading.
524 Eigen::MatrixXd Q = Eigen::MatrixXd::Identity(d, d);
525 {
526 const Eigen::HouseholderQR<Eigen::MatrixXd> qr(directions);
527 Q = qr.householderQ() * Q;
528 Q.leftCols(m) = directions;
529 // Re-orthogonalize the complement against the measured columns.
530 for (Eigen::Index j = m; j < d; ++j) {
531 for (int pass = 0; pass < 2; ++pass)
532 Q.col(j) -= Q.leftCols(j) *
533 (Q.leftCols(j).transpose() * Q.col(j)).eval();
534 const double norm = Q.col(j).norm();
535 if (!(norm > tolerance)) return prepared;
536 Q.col(j) /= norm;
537 }
538 }
539 const Eigen::MatrixXd symmetric_prior = 0.5 * (prior + prior.transpose());
540 const Eigen::MatrixXd P = Q.transpose() * symmetric_prior * Q;
541 const Eigen::MatrixXd Y = Q.transpose() * actions; // column j: H e_j
542 // Independent entry errors rotate into a diagonal approximation of
543 // the rotated covariance: Var(Q^T y)_b = sum_a Q_ab^2 Var(y_a).
544 const Eigen::MatrixXd Qsq = Q.array().square().matrix();
545 const Eigen::MatrixXd V = Qsq.transpose() * variances;
546
547 // Two measurements of one entry, from the two columns that share it,
548 // disagree by their asymmetry; the stencil's own error estimates do
549 // not always see it (a quartic cross term leaves no even residual).
550 // Half the squared asymmetry is added to each of the two entries'
551 // variances: local evidence, applied where it was observed. The
552 // largest ratio of asymmetry to modelled error is reported.
553 Eigen::MatrixXd V_adjusted = V;
554 double inflation = 1.0;
555 for (Eigen::Index i = 0; i < m; ++i) {
556 for (Eigen::Index j = i + 1; j < m; ++j) {
557 const double asymmetry = Y(i, j) - Y(j, i);
558 const double expected = V(i, j) + V(j, i);
559 if (expected > 0.0)
560 inflation =
561 std::max(inflation, asymmetry * asymmetry / expected);
562 V_adjusted(i, j) += 0.5 * asymmetry * asymmetry;
563 V_adjusted(j, i) += 0.5 * asymmetry * asymmetry;
564 }
565 }
566 out.stencil_inflation = inflation;
567
568 // Marginal statistics of every entry (a <= b): precision-weighted mean
569 // of its measurements and the summed precision.
570 Eigen::MatrixXd sum_precision = Eigen::MatrixXd::Zero(d, d);
571 Eigen::MatrixXd sum_weighted = Eigen::MatrixXd::Zero(d, d);
572 // The precision a refinement reaches: the best any refined column's
573 // entry has, or, before any column is refined, the best any entry
574 // has. An entry both of whose columns are refined has nothing left
575 // to gain (17_claisen: floors of 6e-6 under spreads of 0.02 that no
576 // refinement moved bought 27 refinements before the wall).
577 double best_precision = 0.0;
578 double best_refined_precision = 0.0;
579 for (Eigen::Index j = 0; j < m; ++j) {
580 for (Eigen::Index a = 0; a < d; ++a) {
581 const double precision = 1.0 / V_adjusted(a, j);
582 const Eigen::Index row = std::min(a, j), col = std::max(a, j);
583 sum_precision(row, col) += precision;
584 sum_weighted(row, col) += precision * Y(a, j);
585 best_precision = std::max(best_precision, precision);
586 if (columns[static_cast<std::size_t>(j)].refined)
587 best_refined_precision =
588 std::max(best_refined_precision, precision);
589 }
590 }
591 if (best_refined_precision > 0.0) best_precision = best_refined_precision;
592 const auto entry_refined = [&](Eigen::Index a, Eigen::Index b) {
593 const bool a_done =
594 a >= m || columns[static_cast<std::size_t>(a)].refined;
595 const bool b_done =
596 b >= m || columns[static_cast<std::size_t>(b)].refined;
597 return (a < m || b < m) && a_done && b_done;
598 };
599 // The surrogate's eigenbasis in the working basis: W = Q^T V. An
600 // eigenvalue error e_k enters entry (a, b) as e_k W_ak W_bk; a coupling
601 // enters it directly.
602 const Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> surrogate(
603 symmetric_prior);
604 if (surrogate.info() != Eigen::Success) return prepared;
605 const Eigen::MatrixXd W = Q.transpose() * surrogate.eigenvectors();
606 const Eigen::MatrixXd W2 = W.array().square().matrix();
607 const Eigen::VectorXd lambda2 = surrogate.eigenvalues().array().square();
608 const auto prior_coefficients = [&](Eigen::Index a, Eigen::Index b) {
609 const Eigen::ArrayXd shared =
610 (W2.row(a).array() * W2.row(b).array()).transpose();
611 const double f = a == b ? 1.0 : 0.5;
612 return std::array<double, 3>{shared.sum(),
613 (shared * lambda2.array()).sum(), f};
614 };
615 std::vector<std::vector<double>> coefficients(3);
616 std::vector<double> residual_sq, noise;
617 detail::StructuredEntryMarginal joint;
618 const Eigen::Index observed = m * d - m * (m - 1) / 2;
619 joint.loading.resize(observed, d);
620 joint.lambda_squared = lambda2;
621 joint.coupling.resize(observed);
622 joint.noise.resize(observed);
623 joint.residual.resize(observed);
624 Eigen::Index observation = 0;
625 for (Eigen::Index a = 0; a < d; ++a) {
626 for (Eigen::Index b = a; b < d; ++b) {
627 if (!(sum_precision(a, b) > 0.0)) continue;
628 const double mean = sum_weighted(a, b) / sum_precision(a, b);
629 const auto c = prior_coefficients(a, b);
630 for (std::size_t p = 0; p < 3; ++p)
631 coefficients[p].push_back(c[p]);
632 residual_sq.push_back((mean - P(a, b)) * (mean - P(a, b)));
633 noise.push_back(1.0 / sum_precision(a, b));
634 joint.loading.row(observation) =
635 W.row(a).array() * W.row(b).array();
636 joint.coupling(observation) = c[2];
637 joint.noise(observation) = noise.back();
638 joint.residual(observation) = mean - P(a, b);
639 ++observation;
640 }
641 }
642 std::vector<double> fitted;
643 std::vector<double> warm;
644 if (previous != nullptr && previous->valid)
645 warm = {previous->prior_absolute_variance,
646 previous->prior_relative_variance,
647 previous->prior_coupling_variance};
648 detail::maximizeEntryMarginal(coefficients, residual_sq, noise, fitted,
649 warm);
650 // Entry marginals initialize the three scales. Only joint evidence
651 // tests whether the measured contrast lies in their covariance span.
652 const auto initial = fitted;
653 detail::maximizeEntryMarginal(coefficients, residual_sq, noise, fitted,
654 initial, &joint);
655 out.prior_absolute_variance = fitted[0];
656 out.prior_relative_variance = fitted[1];
657 out.prior_coupling_variance = fitted[2];
658 // Eigenvalue errors share a latent coefficient across every matrix
659 // entry. Marginal variances alone do not preserve this covariance.
660 const Eigen::Index entries = d * (d + 1) / 2;
661 const Eigen::VectorXd eigenvalue_deviation =
662 (fitted[0] + fitted[1] * lambda2.array()).sqrt();
663 Eigen::MatrixXd loading(entries, d);
664 Eigen::VectorXd coupling_variance(entries), precision(entries),
665 weighted_residual(entries), floor_precision(entries);
666 Eigen::Index entry = 0;
667 for (Eigen::Index a = 0; a < d; ++a) {
668 for (Eigen::Index b = a; b < d; ++b) {
669 loading.row(entry) = W.row(a).array() * W.row(b).array() *
670 eigenvalue_deviation.transpose().array();
671 coupling_variance(entry) = fitted[2] * (a == b ? 1.0 : 0.5);
672 precision(entry) = sum_precision(a, b);
673 weighted_residual(entry) =
674 sum_weighted(a, b) - precision(entry) * P(a, b);
675 // Symmetry supplies two observations of an off-diagonal entry;
676 // a fully refined entry keeps the precision it has.
677 floor_precision(entry) =
678 entry_refined(a, b) ? std::max(precision(entry), 0.0)
679 : (a == b ? 1.0 : 2.0) * best_precision;
680 ++entry;
681 }
682 }
683 auto posterior = detail::conditionEntryErrors(loading, coupling_variance,
684 precision, weighted_residual);
685 auto floor_posterior = detail::conditionEntryErrors(
686 loading, coupling_variance, floor_precision,
687 Eigen::VectorXd::Zero(entries));
688 if (!posterior.valid || !floor_posterior.valid) return prepared;
689 Eigen::MatrixXd H = P;
690 entry = 0;
691 for (Eigen::Index a = 0; a < d; ++a)
692 for (Eigen::Index b = a; b < d; ++b) {
693 H(a, b) += posterior.mean(entry++);
694 H(b, a) = H(a, b);
695 }
696 const Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> spectrum(H);
697 if (spectrum.info() != Eigen::Success ||
698 !spectrum.eigenvalues().allFinite())
699 return prepared;
700 out.mean_curvatures = spectrum.eigenvalues();
701 out.modes = Q * spectrum.eigenvectors();
702 out.hessian = Q * H * Q.transpose();
703 out.measured_span = directions;
704 prepared.mean = std::move(H);
705 prepared.precision = std::move(precision);
706 prepared.posterior = std::move(posterior);
707 prepared.floor_posterior = std::move(floor_posterior);
708 prepared.valid = out.modes.allFinite() && out.hessian.allFinite();
709 return prepared;
710}
711
712} // namespace detail
713
717 const Eigen::MatrixXd& prior,
718 const std::vector<MeasuredHessianColumn>& columns,
719 const SmoothedCurvatureSpectrum* previous = nullptr,
721{
722 auto prepared = detail::prepareSmoothedCurvature(prior, columns, previous);
723 double failed = prepared.valid ? 0.0 : 1.0;
724 linalg::ordered_sum_bcast(&failed, 1, context);
725 if (failed != 0.0) return {};
726 auto out = std::move(prepared.spectrum);
727 const Eigen::Index d = prior.rows();
728 const Eigen::Index entries = prepared.precision.size();
729 const auto& H = prepared.mean;
730 const auto& precision = prepared.precision;
731 const auto& posterior = prepared.posterior;
732 const auto& floor_posterior = prepared.floor_posterior;
733 // Posterior of the sorted eigenvalues from correlated Gaussian matrix
734 // samples around the posterior mean. The spreads describe posterior
735 // uncertainty; their Monte Carlo estimation error is separate.
736 const Eigen::Index samples = detail::kSpectrumSamples;
737 // Saved stream states reproduce the serial draws without storing an
738 // entries-by-samples noise matrix. Each callback owns its random state.
739 struct RandomState {
740 std::mt19937_64 engine{0x5eedu};
741 std::normal_distribution<double> normal;
742 };
743 RandomState stream;
744 std::vector<RandomState> streams;
745 streams.reserve(samples);
746 for (Eigen::Index n = 0; n < samples; ++n) {
747 streams.push_back(stream);
748 for (Eigen::Index j = 0; j < entries + d; ++j)
749 (void)stream.normal(stream.engine);
750 }
751 Eigen::MatrixXd drawn = Eigen::MatrixXd::Zero(samples, d);
752 Eigen::MatrixXd drawn_floor = drawn, drawn_measured = drawn;
753 Eigen::VectorXi owned = Eigen::VectorXi::Zero(samples);
754 const auto sample = [&](int n) {
755 auto random = streams[static_cast<std::size_t>(n)];
756 Eigen::VectorXd entry_noise(entries), latent_noise(d);
757 for (Eigen::Index j = 0; j < entries; ++j)
758 entry_noise(j) = random.normal(random.engine);
759 for (Eigen::Index k = 0; k < d; ++k)
760 latent_noise(k) = random.normal(random.engine);
761 Eigen::MatrixXd perturbed(d, d);
762 const Eigen::VectorXd draw =
763 posterior.independent_deviation.cwiseProduct(entry_noise) +
764 posterior.correlated_factor * latent_noise;
765 const Eigen::VectorXd floor_draw =
766 floor_posterior.independent_deviation.cwiseProduct(entry_noise) +
767 floor_posterior.correlated_factor * latent_noise;
768 for (int pass = 0; pass < 3; ++pass) {
769 const Eigen::VectorXd& delta = pass == 1 ? floor_draw : draw;
770 perturbed = H;
771 Eigen::Index entry = 0;
772 for (Eigen::Index a = 0; a < d; ++a)
773 for (Eigen::Index b = a; b < d; ++b) {
774 if (pass != 2 || precision(entry) > 0.0)
775 perturbed(a, b) += delta(entry);
776 perturbed(b, a) = perturbed(a, b);
777 ++entry;
778 }
779 const Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> sampled(
780 perturbed, Eigen::EigenvaluesOnly);
781 if (sampled.info() != Eigen::Success ||
782 !sampled.eigenvalues().allFinite())
783 return std::numeric_limits<double>::quiet_NaN();
784 (pass == 0 ? drawn
785 : pass == 1 ? drawn_floor
786 : drawn_measured)
787 .row(n) = sampled.eigenvalues().transpose();
788 }
789 owned(n) = 1;
790 return 1.0;
791 };
792 const auto status = linalg::ProbeExecutor{}.run(
793 static_cast<int>(samples), sample,
795 if (!status.allFinite()) return out;
796 out.local_samples = owned.sum();
797 linalg::disjoint_sum_bcast(drawn.data(), static_cast<int>(drawn.size()),
798 context);
799 linalg::disjoint_sum_bcast(drawn_floor.data(),
800 static_cast<int>(drawn_floor.size()), context);
801 linalg::disjoint_sum_bcast(drawn_measured.data(),
802 static_cast<int>(drawn_measured.size()),
803 context);
804 out.curvatures = drawn.colwise().mean().transpose();
805 out.spreads.resize(d);
806 out.floors.resize(d);
807 out.measured_spreads.resize(d);
808 const Eigen::VectorXd floor_mean = drawn_floor.colwise().mean().transpose();
809 const Eigen::VectorXd measured_mean =
810 drawn_measured.colwise().mean().transpose();
811 const auto deviation = [&](const Eigen::MatrixXd& rows, Eigen::Index k,
812 double mean) {
813 return std::sqrt((rows.col(k).array() - mean).square().sum() /
814 static_cast<double>(samples - 1));
815 };
816 for (Eigen::Index k = 0; k < d; ++k) {
817 out.spreads(k) = deviation(drawn, k, out.curvatures(k));
818 out.floors(k) = deviation(drawn_floor, k, floor_mean(k));
819 out.measured_spreads(k) =
820 deviation(drawn_measured, k, measured_mean(k));
821 }
822 out.valid = out.modes.allFinite() && out.spreads.allFinite() &&
823 out.floors.allFinite() && out.measured_spreads.allFinite();
824 return out;
825}
826
831inline Eigen::VectorXd nextSmoothedCurvatureDirection(
832 const SmoothedCurvatureSpectrum& spectrum, Eigen::Index k)
833{
834 if (!spectrum.valid || k < 0 || k >= spectrum.modes.cols()) return {};
835 Eigen::VectorXd residual = spectrum.modes.col(k);
836 const auto& span = spectrum.measured_span;
837 for (int pass = 0; pass < 2; ++pass)
838 residual -= span * (span.transpose() * residual).eval();
839 const double norm = residual.norm();
840 if (!(norm > std::sqrt(std::numeric_limits<double>::epsilon() *
841 static_cast<double>(residual.size()))))
842 return {};
843 return residual / norm;
844}
845
853inline double measuredUpperBound(
854 const SmoothedCurvatureSpectrum& spectrum,
855 const std::vector<MeasuredHessianColumn>& columns, Eigen::Index k)
856{
857 const double infinity = std::numeric_limits<double>::infinity();
858 if (!spectrum.valid || k < 0 || k >= spectrum.modes.cols() ||
859 columns.empty())
860 return infinity;
861 const Eigen::VectorXd u = spectrum.modes.col(k);
862 const Eigen::Index m = static_cast<Eigen::Index>(columns.size());
863 Eigen::VectorXd weights(m);
864 Eigen::VectorXd in_span = Eigen::VectorXd::Zero(u.size());
865 Eigen::VectorXd action = Eigen::VectorXd::Zero(u.size());
866 for (Eigen::Index j = 0; j < m; ++j) {
867 weights(j) = columns[static_cast<std::size_t>(j)].direction.dot(u);
868 in_span += weights(j) * columns[static_cast<std::size_t>(j)].direction;
869 action += weights(j) * columns[static_cast<std::size_t>(j)].action;
870 }
871 const double outside = (u - in_span).norm();
872 if (!(outside <= std::sqrt(std::numeric_limits<double>::epsilon() *
873 static_cast<double>(u.size()))))
874 return infinity;
875 const double theta = u.dot(action);
876 const double residual = (action - theta * u).norm();
877 return theta + residual;
878}
879
882inline Eigen::VectorXd softestUnmeasuredDirection(
883 const SmoothedCurvatureSpectrum& spectrum)
884{
885 if (!spectrum.valid) return {};
886 const Eigen::Index d = spectrum.hessian.rows();
887 const Eigen::Index m = spectrum.measured_span.cols();
888 if (m >= d) return {};
889 // Orthonormal complement of the measured span.
890 Eigen::MatrixXd Q = Eigen::MatrixXd::Identity(d, d);
891 {
892 const Eigen::HouseholderQR<Eigen::MatrixXd> qr(spectrum.measured_span);
893 Q = qr.householderQ() * Q;
894 }
895 const Eigen::MatrixXd complement = Q.rightCols(d - m);
896 const Eigen::MatrixXd block =
897 complement.transpose() * spectrum.hessian * complement;
898 const Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> solver(
899 0.5 * (block + block.transpose()));
900 if (solver.info() != Eigen::Success) return {};
901 Eigen::VectorXd direction = complement * solver.eigenvectors().col(0);
902 for (int pass = 0; pass < 2; ++pass)
903 direction -= spectrum.measured_span *
904 (spectrum.measured_span.transpose() * direction).eval();
905 const double norm = direction.norm();
906 if (!(norm > 0.0)) return {};
907 return direction / norm;
908}
909
913inline Eigen::Index coarseColumnToRefine(
914 const SmoothedCurvatureSpectrum& spectrum,
915 const std::vector<MeasuredHessianColumn>& columns, Eigen::Index k)
916{
917 if (!spectrum.valid || k < 0 || k >= spectrum.modes.cols()) return -1;
918 const double independence =
919 std::sqrt(std::numeric_limits<double>::epsilon() *
920 static_cast<double>(spectrum.modes.rows()));
921 Eigen::Index best = -1;
922 double best_overlap = independence;
923 for (std::size_t j = 0; j < columns.size(); ++j) {
924 if (columns[j].refined) continue;
925 const double overlap =
926 std::abs(columns[j].direction.dot(spectrum.modes.col(k)));
927 if (overlap > best_overlap) {
928 best_overlap = overlap;
929 best = static_cast<Eigen::Index>(j);
930 }
931 }
932 return best;
933}
934
935} // namespace gpr::optim
@ x
Definition Enums.h:28
@ y
Definition Enums.h:28
MPI-aware dispatcher for the Hutchinson-style probe loop used by the Laplace Hessian assembler and th...
Eigen::VectorXd run(int n_probes, const std::function< double(int)> &probe_fn, KernelInverse::Kind kind, const MpiContext &ctx) const
eon_relax_band_t eon_relax_surface_fn void eon_relax_outcome_t * out
int status
Half surrogate(GaussianProcessRegression &gp, const Eigen::VectorXd &x, Kind kind, const Options &options)
void disjoint_sum_bcast(double *data, int count, const MpiContext &context)
void ordered_sum_bcast(double *data, int count, const MpiContext &context)
double log(double x) noexcept
Eigen::VectorXd softestUnmeasuredDirection(const SmoothedCurvatureSpectrum &spectrum)
double measuredUpperBound(const SmoothedCurvatureSpectrum &spectrum, const std::vector< MeasuredHessianColumn > &columns, Eigen::Index k)
Eigen::VectorXd nextSmoothedCurvatureDirection(const SmoothedCurvatureSpectrum &spectrum, Eigen::Index k)
Eigen::Index coarseColumnToRefine(const SmoothedCurvatureSpectrum &spectrum, const std::vector< MeasuredHessianColumn > &columns, Eigen::Index k)
SmoothedCurvatureSpectrum smoothMeasuredCurvature(const Eigen::MatrixXd &prior, const std::vector< MeasuredHessianColumn > &columns, const SmoothedCurvatureSpectrum *previous=nullptr, const linalg::MpiContext &context=linalg::MpiContext::local())
double variance(const Weights &w, const Matrix &covariance)
std::string line(const std::string &topic, const std::vector< Field > &fields)
static MpiContext local() noexcept
Definition MpiContext.h:75
Eigen::Index local_samples
Spectrum samples evaluated by this process.