Loading...
Searching...
No Matches
SecantHessian.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/Core>
7#include <algorithm>
8#include <cmath>
9#include <cstddef>
10#include <cstdint>
11#include <limits>
12#include <stdexcept>
13#include <string>
14
15namespace gpr::optim {
16
23int bofillThroughLoadedRgsaddle(std::int64_t n, double* hessian_row_major,
24 const double* step,
25 const double* gradient_change);
26
30std::string bofillRgsaddleAbiRefusal();
31
35void setBofillRgsaddleLibrary(const char* path);
36
38
52
54 bool available = false;
55 bool trusted = false;
56 double relative_error = std::numeric_limits<double>::infinity();
57 Eigen::VectorXd direction;
58};
59
66public:
67 explicit SecantHessian(
69 : method_(method)
70 {
71 }
72
73 void reset()
74 {
75 hessian_.resize(0, 0);
76 previous_position_.resize(0);
77 previous_gradient_.resize(0);
78 last_step_.resize(0);
79 last_gradient_change_.resize(0);
80 measured_steps_.resize(0, 0);
81 reference_energy_ = 0.0;
82 has_reference_energy_ = false;
83 pairs_ = 0;
84 }
85
86 [[nodiscard]] bool observe(const Eigen::VectorXd& position,
87 const Eigen::VectorXd& gradient)
88 {
89 if (position.size() == 0 || gradient.size() != position.size() ||
90 !position.allFinite() || !gradient.allFinite())
91 throw std::invalid_argument(
92 "secant observation requires finite matching position and "
93 "gradient");
94 if (previous_position_.size() == 0) {
95 previous_position_ = position;
96 previous_gradient_ = gradient;
97 hessian_ = Eigen::MatrixXd::Zero(position.size(), position.size());
98 return false;
99 }
100 if (position.size() != previous_position_.size())
101 throw std::invalid_argument("secant observation dimension changed");
102
103 const Eigen::VectorXd step = position - previous_position_;
104 const Eigen::VectorXd gradient_change = gradient - previous_gradient_;
105 if (!(step.squaredNorm() > 0.0) || !step.allFinite() ||
106 !gradient_change.allFinite())
107 return false;
108
109 Eigen::MatrixXd candidate = hessian_;
110 if (method_ == SecantHessianMethod::BFGS && pairs_ == 0) {
111 const double ss = step.squaredNorm();
112 const double ys = gradient_change.dot(step);
113 if (!bfgsCurvatureResolved(gradient_change, step, ys) ||
114 !std::isfinite(ss))
115 return false;
116 candidate.diagonal().setConstant(ys / ss);
117 }
118
119 // A repeated secant relation is an accepted no-op. Its resolution
120 // is relative to the two competing Hessian actions: a dimensionless
121 // absolute floor would classify small, exactly represented pairs by
122 // their units. Do not bypass BFGS's positive-curvature condition.
123 const Eigen::VectorXd action = candidate * step;
124 const Eigen::VectorXd residual = gradient_change - action;
125 const double action_scale =
126 std::max(gradient_change.norm(), action.norm());
127 const double resolution =
128 std::sqrt(std::numeric_limits<double>::epsilon()) * action_scale;
129 const double ys = gradient_change.dot(step);
130 if (pairs_ > 0 && residual.norm() <= resolution &&
131 (method_ != SecantHessianMethod::BFGS ||
132 (ys > 0.0 && std::isfinite(ys)))) {
133 previous_position_ = position;
134 previous_gradient_ = gradient;
135 last_step_ = step;
136 last_gradient_change_ = gradient_change;
137 appendMeasuredStep(step);
138 ++pairs_;
139 return true;
140 }
141
142 const bool updated = update(candidate, method_, step, gradient_change);
143 if (!updated || !candidate.allFinite()) return false;
144 hessian_ = (0.5 * (candidate + candidate.transpose())).eval();
145 previous_position_ = position;
146 previous_gradient_ = gradient;
147 last_step_ = step;
148 last_gradient_change_ = gradient_change;
149 appendMeasuredStep(step);
150 ++pairs_;
151 return true;
152 }
153
160 [[nodiscard]] bool observe(const Eigen::VectorXd& position,
161 const Eigen::VectorXd& gradient, double energy)
162 {
163 const bool first = previous_position_.size() == 0;
164 const bool accepted = observe(position, gradient);
165 if (accepted || first) noteEnergy(energy);
166 return accepted;
167 }
168
171 void noteEnergy(double energy)
172 {
173 if (!std::isfinite(energy)) {
174 has_reference_energy_ = false;
175 return;
176 }
177 reference_energy_ = energy;
178 has_reference_energy_ = true;
179 }
180
181 [[nodiscard]] bool hasReferenceEnergy() const noexcept
182 {
183 return has_reference_energy_;
184 }
185
186 [[nodiscard]] double referenceEnergy() const
187 {
188 if (!has_reference_energy_)
189 throw std::logic_error(
190 "quadratic secant mean requires a recorded reference energy");
191 return reference_energy_;
192 }
193
194 [[nodiscard]] bool available() const noexcept
195 {
196 return pairs_ > 0 && hessian_.rows() > 0;
197 }
198 [[nodiscard]] std::size_t pairs() const noexcept
199 {
200 return pairs_;
201 }
202 [[nodiscard]] const Eigen::MatrixXd& hessian() const noexcept
203 {
204 return hessian_;
205 }
206 [[nodiscard]] const Eigen::VectorXd& referencePosition() const noexcept
207 {
208 return previous_position_;
209 }
210 [[nodiscard]] const Eigen::VectorXd& referenceGradient() const noexcept
211 {
212 return previous_gradient_;
213 }
214 [[nodiscard]] const Eigen::VectorXd& lastDirection() const noexcept
215 {
216 return last_step_;
217 }
218
222 [[nodiscard]] const Eigen::MatrixXd& measuredSteps() const noexcept
223 {
224 return measured_steps_;
225 }
227 const Eigen::VectorXd& posterior_action,
228 double relative_tolerance) const
229 {
230 SecantConsistency result;
231 if (!available() || last_step_.size() == 0 ||
232 posterior_action.size() != last_step_.size() ||
233 !posterior_action.allFinite() || !(relative_tolerance >= 0.0) ||
234 !std::isfinite(relative_tolerance))
235 return result;
236 const double length = last_step_.norm();
237 if (!(length > 0.0) || !std::isfinite(length)) return result;
238 result.direction = last_step_ / length;
239 const Eigen::VectorXd measured = last_gradient_change_ / length;
240 const double scale = std::max({measured.norm(), posterior_action.norm(),
241 std::numeric_limits<double>::min()});
242 result.relative_error = (posterior_action - measured).norm() / scale;
243 result.available = std::isfinite(result.relative_error);
244 result.trusted =
245 result.available && result.relative_error <= relative_tolerance;
246 return result;
247 }
248
249 [[nodiscard]] double meanEnergy(const Eigen::VectorXd& position,
250 double reference_energy) const
251 {
252 requireMeanPoint(position, reference_energy);
253 const Eigen::VectorXd displacement = position - previous_position_;
254 return reference_energy + previous_gradient_.dot(displacement) +
255 0.5 * displacement.dot(hessian_ * displacement);
256 }
257
258 [[nodiscard]] Eigen::VectorXd meanGradient(
259 const Eigen::VectorXd& position) const
260 {
261 requireMeanPoint(position, 0.0);
262 return previous_gradient_ + hessian_ * (position - previous_position_);
263 }
264
267 static bool update(Eigen::MatrixXd& matrix, SecantHessianMethod method,
268 const Eigen::VectorXd& step,
269 const Eigen::VectorXd& gradient_change)
270 {
271 if (matrix.rows() == 0 || matrix.rows() != matrix.cols() ||
272 step.size() != matrix.rows() ||
273 gradient_change.size() != matrix.rows() || !matrix.allFinite() ||
274 !step.allFinite() || !gradient_change.allFinite())
275 return false;
276 switch (method) {
278 return updateBfgs(matrix, step, gradient_change);
280 return updateSr1(matrix, step, gradient_change);
282 return updateBofill(matrix, step, gradient_change);
283 }
284 return false;
285 }
286
287private:
294 static bool bfgsCurvatureResolved(const Eigen::VectorXd& gradient_change,
295 const Eigen::VectorXd& step, double ys)
296 {
297 const double resolution =
298 std::sqrt(std::numeric_limits<double>::epsilon()) *
299 gradient_change.norm() * step.norm();
300 return std::isfinite(ys) && ys > resolution;
301 }
302
303 void appendMeasuredStep(const Eigen::VectorXd& step)
304 {
305 const double length = step.norm();
306 if (!(length > 0.0) || !std::isfinite(length)) return;
307 if (measured_steps_.rows() != step.size())
308 measured_steps_ = Eigen::MatrixXd(step.size(), 0);
309 Eigen::VectorXd direction = step / length;
310 // Reorthogonalise to suppress the accumulated projection residue.
311 for (int pass = 0; pass < 2; ++pass)
312 direction -=
313 measured_steps_ * (measured_steps_.transpose() * direction);
314 const double outside = direction.norm();
315 if (!(outside > std::sqrt(std::numeric_limits<double>::epsilon())))
316 return;
317 const Eigen::Index column = measured_steps_.cols();
318 measured_steps_.conservativeResize(step.size(), column + 1);
319 measured_steps_.col(column) = direction / outside;
320 }
321
325 static bool updateBfgs(Eigen::MatrixXd& matrix, const Eigen::VectorXd& step,
326 const Eigen::VectorXd& gradient_change);
327
332 static bool updateSr1(Eigen::MatrixXd& matrix, const Eigen::VectorXd& step,
333 const Eigen::VectorXd& gradient_change);
334
340 static bool updateBofill(Eigen::MatrixXd& matrix,
341 const Eigen::VectorXd& step,
342 const Eigen::VectorXd& gradient_change);
343
344 void requireMeanPoint(const Eigen::VectorXd& position, double energy) const
345 {
346 if (!available() || position.size() != hessian_.rows() ||
347 !position.allFinite() || !std::isfinite(energy))
348 throw std::logic_error(
349 "quadratic secant mean requires an available matching model");
350 }
351
352 SecantHessianMethod method_;
353 Eigen::MatrixXd hessian_;
354 Eigen::VectorXd previous_position_;
355 Eigen::VectorXd previous_gradient_;
356 Eigen::VectorXd last_step_;
357 Eigen::VectorXd last_gradient_change_;
358 Eigen::MatrixXd measured_steps_;
359 double reference_energy_ = 0.0;
360 bool has_reference_energy_ = false;
361 std::size_t pairs_ = 0;
362};
363
364} // namespace gpr::optim
bool available() const noexcept
bool hasReferenceEnergy() const noexcept
SecantConsistency consistency(const Eigen::VectorXd &posterior_action, double relative_tolerance) const
bool observe(const Eigen::VectorXd &position, const Eigen::VectorXd &gradient, double energy)
const Eigen::VectorXd & referenceGradient() const noexcept
double meanEnergy(const Eigen::VectorXd &position, double reference_energy) const
SecantHessian(SecantHessianMethod method=SecantHessianMethod::Bofill)
const Eigen::VectorXd & lastDirection() const noexcept
Eigen::VectorXd meanGradient(const Eigen::VectorXd &position) const
const Eigen::MatrixXd & hessian() const noexcept
const Eigen::MatrixXd & measuredSteps() const noexcept
const Eigen::VectorXd & referencePosition() const noexcept
void noteEnergy(double energy)
double referenceEnergy() const
static bool update(Eigen::MatrixXd &matrix, SecantHessianMethod method, const Eigen::VectorXd &step, const Eigen::VectorXd &gradient_change)
bool observe(const Eigen::VectorXd &position, const Eigen::VectorXd &gradient)
std::size_t pairs() const noexcept
std::string bofillRgsaddleAbiRefusal()
int bofillThroughLoadedRgsaddle(std::int64_t n, double *hessian_row_major, const double *step, const double *gradient_change)
void setBofillRgsaddleLibrary(const char *path)
bool enabled() const noexcept