Loading...
Searching...
No Matches
SecantCurvature.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/Core>
8#include <Eigen/Eigenvalues>
9#include <Eigen/QR>
10#include <cmath>
11#include <iosfwd>
12#include <limits>
13#include <optional>
14#include <stdexcept>
15#include <utility>
16#include <vector>
17
19
20namespace gpr::optim {
21
31
32inline void writeSecantCurvatureCounts(std::ostream& out,
33 const SecantCurvatureCounts& counts)
34{
35 out << "Secant pairs accepted: " << counts.pairs_accepted << "\n";
36 out << "Secant pairs rejected: " << counts.pairs_rejected << "\n";
37 out << "Secant HVP calls: " << counts.hvp_calls << "\n";
38 out << "Secant Hessian-consistency rejections: "
39 << counts.consistency_rejections << "\n";
40 out << "Secant quadratic-mean uses: " << counts.quadratic_mean_uses << "\n";
41}
42
47
52 SecantHessian& secant, const Eigen::VectorXd& position,
53 const Eigen::VectorXd& gradient, double energy,
56{
57 const bool had_reference =
58 secant.referencePosition().size() == position.size();
59 const bool moved =
60 had_reference &&
61 (secant.referencePosition() - position).squaredNorm() > 0.0;
62 const bool accepted = secant.observe(position, gradient, energy);
63 if (accounting == SecantAccounting::AlreadyCounted) return;
64 if (accepted)
65 ++counts.pairs_accepted;
66 else if (moved)
67 ++counts.pairs_rejected;
68}
69
80
81[[nodiscard]] inline const char* secantSeedStatusName(
82 SecantSeedStatus status) noexcept
83{
84 switch (status) {
86 return "seeded";
88 return "no accepted pair";
90 return "secant and model dimensions differ";
92 return "no resolved curvature";
94 return "no usable current direction";
96 return "not positive definite";
97 }
98 return "unknown";
99}
100
107inline std::optional<Eigen::VectorXd> secantResolvedNegativeMode(
108 const SecantHessian& secant)
109{
110 if (!secant.available()) return std::nullopt;
111 const Eigen::MatrixXd& basis = secant.measuredSteps();
112 if (basis.rows() != secant.hessian().rows() || basis.cols() == 0)
113 return std::nullopt;
114 const Eigen::MatrixXd projected =
115 basis.transpose() * secant.hessian() * basis;
116 const Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> spectrum(
117 0.5 * (projected + projected.transpose()));
118 if (spectrum.info() != Eigen::Success ||
119 !spectrum.eigenvalues().allFinite() ||
120 !spectrum.eigenvectors().allFinite())
121 throw std::runtime_error("secant curvature seed eigensolve failed");
122 const double scale = spectrum.eigenvalues().cwiseAbs().maxCoeff();
123 const double tolerance =
124 scale * std::sqrt(std::numeric_limits<double>::epsilon());
125 if (!(spectrum.eigenvalues()(0) < -tolerance)) return std::nullopt;
126 Eigen::VectorXd mode = basis * spectrum.eigenvectors().col(0);
127 const double norm = mode.norm();
128 if (!(norm > 0.0) || !std::isfinite(norm))
129 throw std::runtime_error("secant curvature seed mode is degenerate");
130 mode /= norm;
131 return mode;
132}
133
143
144[[nodiscard]] inline SecantSeed secantSeedDirection(
145 const SecantHessian& secant, const Eigen::VectorXd& current_direction)
146{
147 SecantSeed seed;
148 const double norm = current_direction.norm();
149 const bool usable = current_direction.size() > 0 &&
150 current_direction.allFinite() && norm > 0.0 &&
151 std::isfinite(norm);
152 if (usable) seed.direction = current_direction / norm;
153 if (!secant.available()) {
155 return seed;
156 }
157 if (!usable) {
159 return seed;
160 }
161 if (seed.direction.size() != secant.hessian().rows()) {
163 return seed;
164 }
165 std::optional<Eigen::VectorXd> mode = secantResolvedNegativeMode(secant);
166 if (!mode) {
168 return seed;
169 }
170 if (mode->dot(seed.direction) < 0.0) *mode *= -1.0;
171 seed.direction = std::move(*mode);
173 return seed;
174}
175
179inline std::optional<double> secantPositiveInverseScale(
180 const SecantHessian& secant)
181{
182 if (!secant.available()) return std::nullopt;
183 const Eigen::VectorXd& step = secant.lastDirection();
184 const double ss = step.squaredNorm();
185 if (!(ss > 0.0) || !step.allFinite()) return std::nullopt;
186 const double curvature = step.dot(secant.hessian() * step) / ss;
187 if (!(curvature > 0.0) || !std::isfinite(curvature)) return std::nullopt;
188 return 1.0 / curvature;
189}
190
199
201 const SecantHessian& secant)
202{
204 if (!secant.available()) return out;
205 const Eigen::MatrixXd symmetric =
206 0.5 * (secant.hessian() + secant.hessian().transpose());
207 const Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> spectrum(
208 symmetric, Eigen::EigenvaluesOnly);
209 if (spectrum.info() != Eigen::Success ||
210 !spectrum.eigenvalues().allFinite()) {
212 return out;
213 }
214 const double scale = spectrum.eigenvalues().cwiseAbs().maxCoeff();
215 if (!(scale > 0.0)) {
217 return out;
218 }
219 if (!(spectrum.eigenvalues().minCoeff() >
220 scale * std::sqrt(std::numeric_limits<double>::epsilon()))) {
222 return out;
223 }
224 out.factor.compute(symmetric);
225 out.status = out.factor.info() == Eigen::Success
228 return out;
229}
230
238
239namespace detail {
240
244[[nodiscard]] inline SecantSeedStatus seedModelOnRitzSpan(
245 Eigen::MatrixXd& model, const Eigen::MatrixXd& ritz,
246 const Eigen::MatrixXd* basis)
247{
248 const Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> spectrum(ritz);
249 if (spectrum.info() != Eigen::Success ||
250 !spectrum.eigenvalues().allFinite() ||
251 !spectrum.eigenvectors().allFinite())
252 throw std::runtime_error("secant curvature seed eigensolve failed");
253 const double scale = spectrum.eigenvalues().cwiseAbs().maxCoeff();
254 const double tolerance =
255 scale * std::sqrt(std::numeric_limits<double>::epsilon());
256 Eigen::MatrixXd span(model.rows(), 0);
257 Eigen::VectorXd values(0);
258 for (Eigen::Index k = 0; k < spectrum.eigenvalues().size(); ++k) {
259 if (!(std::abs(spectrum.eigenvalues()(k)) > tolerance)) continue;
260 const Eigen::Index column = span.cols();
261 span.conservativeResize(model.rows(), column + 1);
262 values.conservativeResize(column + 1);
263 span.col(column) =
264 basis != nullptr
265 ? Eigen::VectorXd(*basis * spectrum.eigenvectors().col(k))
266 : Eigen::VectorXd(spectrum.eigenvectors().col(k));
267 values(column) = spectrum.eigenvalues()(k);
268 }
269 if (span.cols() == 0) return SecantSeedStatus::NoResolvedCurvature;
270 const Eigen::MatrixXd complement =
271 Eigen::MatrixXd::Identity(model.rows(), model.cols()) -
272 span * span.transpose();
273 model = complement * model * complement +
274 span * values.asDiagonal() * span.transpose();
275 model = 0.5 * (model + model.transpose());
277}
278
279} // namespace detail
280
287 Eigen::MatrixXd& model, const Eigen::MatrixXd& secant_hessian)
288{
289 if (model.rows() == 0 || model.rows() != model.cols() ||
290 secant_hessian.rows() != model.rows() ||
291 secant_hessian.cols() != model.cols() || !model.allFinite() ||
292 !secant_hessian.allFinite())
293 throw std::invalid_argument(
294 "secant curvature seed requires matching finite Hessians");
295 const Eigen::MatrixXd symmetric =
296 0.5 * (secant_hessian + secant_hessian.transpose());
297 return detail::seedModelOnRitzSpan(model, symmetric, nullptr);
298}
299
306 Eigen::MatrixXd& model, const Eigen::MatrixXd& secant_hessian,
307 const Eigen::MatrixXd& measured_steps)
308{
309 if (model.rows() == 0 || model.rows() != model.cols() ||
310 secant_hessian.rows() != model.rows() ||
311 secant_hessian.cols() != model.cols() || !model.allFinite() ||
312 !secant_hessian.allFinite() || measured_steps.rows() != model.rows() ||
313 !measured_steps.allFinite())
314 throw std::invalid_argument(
315 "secant curvature seed requires matching finite Hessians and "
316 "steps");
317 if (measured_steps.cols() == 0)
319 const Eigen::ColPivHouseholderQR<Eigen::MatrixXd> step_qr(measured_steps);
320 const Eigen::Index rank = step_qr.rank();
321 if (rank == 0) return SecantSeedStatus::NoResolvedCurvature;
322 const Eigen::MatrixXd basis =
323 step_qr.householderQ() * Eigen::MatrixXd::Identity(model.rows(), rank);
324 const Eigen::MatrixXd symmetric =
325 0.5 * (secant_hessian + secant_hessian.transpose());
326 const Eigen::MatrixXd projected = basis.transpose() * symmetric * basis;
327 return detail::seedModelOnRitzSpan(
328 model, 0.5 * (projected + projected.transpose()), &basis);
329}
330
343 Eigen::MatrixXd& model, const SecantHessian& secant,
344 const Eigen::MatrixXd& weight,
346{
347 if (!secant.available()) return SecantSeedStatus::NoAcceptedPair;
348 if (secant.hessian().rows() != model.rows() ||
349 weight.rows() != model.rows() || weight.cols() != model.cols())
351 const Eigen::MatrixXd weighted = secant.hessian().cwiseProduct(weight);
352 if (support == SecantSeedSupport::WholeHessian)
353 return seedHessianOnSecantRange(model, weighted);
354 const Eigen::VectorXd diagonal = weight.diagonal();
355 if (!(diagonal.array() > 0.0).all() || !diagonal.allFinite())
356 throw std::invalid_argument(
357 "measured-step secant seed requires a positive coordinate weight");
358 const Eigen::MatrixXd steps =
359 (secant.measuredSteps().array().colwise() / diagonal.array().sqrt())
360 .matrix();
361 return seedHessianOnMeasuredStepRange(model, weighted, steps);
362}
363
367 Eigen::VectorXd position;
368 Eigen::VectorXd gradient;
369 double energy = 0.0;
370};
371
375template <class Prior>
377 SecantHessianMethod method, const std::vector<SecantForceSample>& samples,
378 Prior&& prior)
379{
380 SecantHessian secant(method);
382 for (const SecantForceSample& sample: samples) {
383 double prior_energy = 0.0;
384 Eigen::VectorXd prior_gradient;
385 prior(sample.position, prior_energy, prior_gradient);
386 if (!std::isfinite(prior_energy) ||
387 prior_gradient.size() != sample.gradient.size() ||
388 !prior_gradient.allFinite())
389 throw std::runtime_error(
390 "secant quadratic mean requires a finite prior gradient");
391 recordSecantObservation(secant, sample.position,
392 sample.gradient - prior_gradient,
393 sample.energy - prior_energy, counts);
394 }
395 return secant;
396}
397
398} // namespace gpr::optim
bool available() const noexcept
const Eigen::VectorXd & lastDirection() const noexcept
const Eigen::MatrixXd & hessian() const noexcept
const Eigen::MatrixXd & measuredSteps() const noexcept
const Eigen::VectorXd & referencePosition() const noexcept
bool observe(const Eigen::VectorXd &position, const Eigen::VectorXd &gradient)
eon_relax_band_t eon_relax_surface_fn void eon_relax_outcome_t * out
int status
std::optional< double > secantPositiveInverseScale(const SecantHessian &secant)
SecantHessian secantFittedToResidual(SecantHessianMethod method, const std::vector< SecantForceSample > &samples, Prior &&prior)
std::optional< Eigen::VectorXd > secantResolvedNegativeMode(const SecantHessian &secant)
void recordSecantObservation(SecantHessian &secant, const Eigen::VectorXd &position, const Eigen::VectorXd &gradient, double energy, SecantCurvatureCounts &counts, SecantAccounting accounting=SecantAccounting::Count)
SecantSeedStatus seedHessianOnSecantRange(Eigen::MatrixXd &model, const Eigen::MatrixXd &secant_hessian)
SecantNewtonFactor secantNewtonFactor(const SecantHessian &secant)
SecantSeed secantSeedDirection(const SecantHessian &secant, const Eigen::VectorXd &current_direction)
SecantSeedStatus seedHessianFromSecant(Eigen::MatrixXd &model, const SecantHessian &secant, const Eigen::MatrixXd &weight, SecantSeedSupport support=SecantSeedSupport::WholeHessian)
void writeSecantCurvatureCounts(std::ostream &out, const SecantCurvatureCounts &counts)
SecantSeedStatus seedHessianOnMeasuredStepRange(Eigen::MatrixXd &model, const Eigen::MatrixXd &secant_hessian, const Eigen::MatrixXd &measured_steps)
const char * secantSeedStatusName(SecantSeedStatus status) noexcept
Eigen::LLT< Eigen::MatrixXd > factor
Eigen::VectorXd direction
SecantSeedStatus status