Loading...
Searching...
No Matches
AffineGaussianArcModel.h
Go to the documentation of this file.
1// SPDX-License-Identifier: MIT
6#pragma once
7#include <algorithm>
8#include <functional>
9#include <memory>
10#include <numeric>
11#include <vector>
12
13#include "AffineGaussianJet.h"
14#include "PotentialPath.h"
15
16namespace gpr::quantum {
26
27// Coordinates belong to one unwrapped physical chart supplied by the geometry
28// layer. The quadratic mean is deterministic; this GP supplies search
29// proposals. Physical rate curvature is assessed independently of the fitted
30// posterior.
32 using V = Eigen::VectorXd;
33 using M = Eigen::MatrixXd;
34 MassMetric metric_;
35 M well_;
37 std::vector<V> points_;
38 std::vector<PotentialEvaluation> values_;
39 std::vector<std::size_t> fittedOwners_;
40 std::unique_ptr<AffineGaussianJet> posterior_;
41 std::size_t fittedSites_{}, fitEvaluations_{};
42 Eigen::Index fittedSpan_{}, fittedTangent_{}, fittedNormal_{};
43 double fittedLength_{};
44 bool converged_{};
45 static void require(bool yes, const char* message)
46 {
47 if (!yes) throw std::invalid_argument(message);
48 }
49 Eigen::Index find(const V& q) const
50 {
51 const V physical = metric_.physical(q);
52 for (std::size_t i = 0; i < points_.size(); ++i) {
53 const V candidate = metric_.physical(points_[i]);
54 const double scale = std::max({1., physical.cwiseAbs().maxCoeff(),
55 candidate.cwiseAbs().maxCoeff()});
56 if ((physical - candidate).cwiseAbs().maxCoeff() <=
57 128 * std::numeric_limits<double>::epsilon() * scale)
58 return i;
59 }
60 return -1;
61 }
62 void fit(const std::vector<std::size_t>& selected)
63 {
64 require(!selected.empty(),
65 "At least one native Gaussian observation required");
66 posterior_.reset();
67 fittedOwners_.clear();
68 fittedSites_ = 0;
69 fittedSpan_ = fittedTangent_ = fittedNormal_ = 0;
70 const auto n = selected.size();
71 const auto d = metric_.dimension();
72 M x(n, d), g(n, d);
73 V e(n);
74 for (std::size_t i = 0; i < n; ++i) {
75 const auto owner = selected[i];
76 const V background = well_ * points_[owner];
77 x.row(i) = metric_.physical(points_[owner]).transpose();
78 e[i] = values_[owner].energy - .5 * points_[owner].dot(background);
79 g.row(i) = ((values_[owner].gradient - background).array() *
80 metric_.roots().array())
81 .matrix()
82 .transpose();
83 }
84 std::vector<double> distances;
85 for (std::size_t i = 0; i < n; ++i)
86 for (std::size_t j = 0; j < i; ++j) {
87 const double distance = (x.row(i) - x.row(j)).norm();
88 if (distance > 0) distances.push_back(distance);
89 }
90 double pivot = options_.initialLength;
91 if (!(pivot > 0)) {
92 if (distances.empty())
93 pivot = 1.;
94 else {
95 const auto mid = distances.begin() + distances.size() / 2;
96 std::nth_element(distances.begin(), mid, distances.end());
97 pivot = *mid;
98 }
99 }
100 const double lower =
101 options_.minimumLength > 0 ? options_.minimumLength : pivot / 16;
102 const double upper =
103 options_.maximumLength > 0 ? options_.maximumLength : pivot * 16;
104 require(lower > 0 && upper >= lower && std::isfinite(upper),
105 "Finite ordered Gaussian length bounds required");
106 const double lo = std::log(lower), hi = std::log(upper);
107 fitEvaluations_ = 0;
108 converged_ = false;
109 std::unique_ptr<AffineGaussianJet> best;
110 double score = std::numeric_limits<double>::infinity(), bestLog = 0;
111 std::vector<std::pair<double, double>> evaluated;
112 auto available = [&] {
113 return !options_.maximumFitEvaluations ||
114 fitEvaluations_ < options_.maximumFitEvaluations;
115 };
116 auto evaluate = [&](double t) {
117 ++fitEvaluations_;
118 double value = std::numeric_limits<double>::infinity();
119 try {
120 auto candidate = std::make_unique<AffineGaussianJet>(
121 x, e, g, std::exp(t), options_.signalVariance,
122 options_.energyNoiseVariance,
123 options_.gradientNoiseVariance);
124 value = candidate->negativeLogLikelihood();
125 if (value < score) {
126 score = value;
127 bestLog = t;
128 best = std::move(candidate);
129 }
130 } catch (const std::runtime_error&) {
131 }
132 evaluated.emplace_back(t, value);
133 return value;
134 };
135 evaluate(std::clamp(
136 fittedLength_ > 0 ? std::log(fittedLength_) : std::log(pivot), lo,
137 hi));
138 if (upper > lower) {
139 for (unsigned j = 0; j < 9 && available(); ++j) {
140 const double t = lo + (hi - lo) * j / 8.;
141 if (std::none_of(evaluated.begin(), evaluated.end(),
142 [&](const auto& v) { return v.first == t; }))
143 evaluate(t);
144 }
145 if (best && available()) {
146 std::sort(evaluated.begin(), evaluated.end());
147 double left = lo, right = hi;
148 for (const auto& sample: evaluated) {
149 if (sample.first < bestLog) left = sample.first;
150 if (sample.first > bestLog) {
151 right = sample.first;
152 break;
153 }
154 }
155 constexpr double fraction = .3819660112501051518;
156 while (available() &&
157 right - left > options_.logLengthTolerance) {
158 const double t =
159 bestLog - left > right - bestLog
160 ? bestLog - fraction * (bestLog - left)
161 : bestLog + fraction * (right - bestLog);
162 const double previous = bestLog;
163 const double value = evaluate(t);
164 if (bestLog != previous) {
165 if (t < previous)
166 right = previous;
167 else
168 left = previous;
169 } else if (t < previous)
170 left = t;
171 else
172 right = t;
173 if (!std::isfinite(value) && left == right) break;
174 }
175 converged_ = right - left <= options_.logLengthTolerance;
176 }
177 } else
178 converged_ = true;
179 require(
180 bool(best),
181 "No positive Gaussian covariance exists within the length bounds");
182 fittedSpan_ = best->spanDimension();
183 fittedTangent_ = best->tangentFactorDimension();
184 fittedNormal_ = best->normalFactorDimension();
185 posterior_ = std::move(best);
186 fittedSites_ = n;
187 fittedOwners_ = selected;
188 fittedLength_ = std::exp(bestLog);
189 }
190
191public:
196 AffineGaussianArcOptions options = {})
197 : metric_(std::move(metric)), well_(std::move(well)), options_(options)
198 {
199 require(well_.rows() == metric_.dimension() &&
200 well_.cols() == metric_.dimension() && well_.allFinite() &&
201 (well_ - well_.transpose()).norm() <=
202 1e-12 * std::max(1., well_.norm()),
203 "Finite symmetric Gaussian background curvature required");
204 require(
205 options_.signalVariance > 0 && options_.energyNoiseVariance > 0 &&
206 options_.gradientNoiseVariance > 0 &&
207 options_.logLengthTolerance > 0 &&
208 std::isfinite(options_.signalVariance) &&
209 std::isfinite(options_.energyNoiseVariance) &&
210 std::isfinite(options_.gradientNoiseVariance) &&
211 std::isfinite(options_.logLengthTolerance) &&
212 options_.initialLength >= 0 &&
213 std::isfinite(options_.initialLength) &&
214 options_.minimumLength >= 0 &&
215 std::isfinite(options_.minimumLength) &&
216 options_.maximumLength >= 0 &&
217 std::isfinite(options_.maximumLength),
218 "Positive Gaussian prior and finite observation controls required");
219 }
220 std::size_t addObservations(const std::vector<V>& q,
221 const std::vector<PotentialEvaluation>& values)
222 {
223 require(q.size() == values.size(),
224 "Matching native energy-gradient observations required");
225 std::size_t added = 0;
226 for (std::size_t i = 0; i < q.size(); ++i) {
227 require(q[i].size() == metric_.dimension() && q[i].allFinite() &&
228 values[i].gradient.size() == metric_.dimension() &&
229 values[i].gradient.allFinite() &&
230 std::isfinite(values[i].energy),
231 "Finite native observations in the supplied mass metric "
232 "required");
233 if (find(q[i]) >= 0) continue;
234 points_.push_back(q[i]);
235 values_.push_back(values[i]);
236 ++added;
237 }
238 if (added) posterior_.reset();
239 return added;
240 }
241 void refitLocal(const std::vector<V>& q,
242 const std::vector<PotentialEvaluation>& values,
243 std::size_t maximumSites)
244 {
245 require(!q.empty() && maximumSites > 0,
246 "Positive native Gaussian training budget required");
247 addObservations(q, values);
248 std::vector<std::size_t> selected;
249 std::vector<bool> required(points_.size(), false);
250 for (const auto& point: q) {
251 const auto index = find(point);
252 require(index >= 0, "Requested native observation is absent");
253 if (!required[index]) {
254 required[index] = true;
255 selected.push_back(index);
256 }
257 }
258 require(selected.size() <= maximumSites,
259 "Training budget cannot exclude a requested native site");
260 if (options_.archiveSelection ==
262 std::vector<std::pair<double, std::size_t>> candidates;
263 for (std::size_t i = 0; i < points_.size(); ++i)
264 if (!required[i]) {
265 double distance = std::numeric_limits<double>::infinity();
266 for (const auto& point: q)
267 distance = std::min(distance,
268 (point - points_[i]).squaredNorm());
269 candidates.emplace_back(distance, i);
270 }
271 std::stable_sort(candidates.begin(), candidates.end());
272 for (const auto& candidate: candidates) {
273 if (selected.size() == maximumSites) break;
274 selected.push_back(candidate.second);
275 }
276 fit(selected);
277 return;
278 }
279 // Each distinct current site receives one archived neighbour per
280 // round, so density at one endpoint cannot consume the band budget.
281 using Candidate = std::pair<double, std::size_t>;
282 std::vector<std::vector<Candidate>> neighbours(selected.size());
283 for (std::size_t anchor = 0; anchor < selected.size(); ++anchor) {
284 auto& candidates = neighbours[anchor];
285 for (std::size_t i = 0; i < points_.size(); ++i)
286 if (!required[i])
287 candidates.emplace_back(
288 (points_[selected[anchor]] - points_[i]).squaredNorm(),
289 i);
290 std::stable_sort(candidates.begin(), candidates.end());
291 }
292 std::vector<std::size_t> cursor(neighbours.size(), 0);
293 while (selected.size() < maximumSites &&
294 selected.size() < points_.size()) {
295 const auto previous = selected.size();
296 for (std::size_t anchor = 0; anchor < neighbours.size(); ++anchor) {
297 auto& next = cursor[anchor];
298 const auto& candidates = neighbours[anchor];
299 while (next < candidates.size() &&
300 required[candidates[next].second])
301 ++next;
302 if (next == candidates.size()) continue;
303 const auto owner = candidates[next++].second;
304 required[owner] = true;
305 selected.push_back(owner);
306 if (selected.size() == maximumSites) break;
307 }
308 if (selected.size() == previous) break;
309 }
310 fit(selected);
311 }
312 void refit(const std::vector<V>& q,
313 const std::vector<PotentialEvaluation>& values)
314 {
315 addObservations(q, values);
316 std::vector<std::size_t> all(points_.size());
317 std::iota(all.begin(), all.end(), 0);
318 fit(all);
319 }
320 std::vector<PotentialEvaluation> evaluate(const std::vector<V>& q) const
321 {
322 require(
323 bool(posterior_),
324 "Native Gaussian observations require fitting before prediction");
325 std::vector<PotentialEvaluation> result;
326 for (const auto& point: q) {
327 const auto predicted =
328 posterior_->predict(metric_.physical(point), false);
329 result.push_back(
330 {predicted.energy + .5 * point.dot(well_ * point),
331 metric_.gradient(predicted.gradient) + well_ * point});
332 }
333 return result;
334 }
335 std::function<bool(const V&, V&)> prepareHessian(const V& point) const
336 {
337 require(bool(posterior_),
338 "A fitted Gaussian posterior is required for search curvature");
339 const auto predicted =
340 posterior_->predict(metric_.physical(point), false);
341 const M curvature = well_ + metric_.hessian(predicted.hessian);
342 return [curvature](const V& direction, V& result) {
343 if (direction.size() != curvature.cols()) return false;
344 result = curvature * direction;
345 return result.allFinite();
346 };
347 }
348 std::vector<PointVariance> posteriorPointVariance(
349 const std::vector<V>& q) const
350 {
351 require(bool(posterior_),
352 "A fitted Gaussian posterior is required for uncertainty");
353 std::vector<PointVariance> result;
354 for (const auto& point: q) {
355 const auto predicted = posterior_->predict(metric_.physical(point));
356 const double scale =
357 options_.signalVariance / (fittedLength_ * fittedLength_);
358 require(predicted.energyVariance >=
359 -1e-12 * std::max(1., options_.signalVariance) &&
360 predicted.gradientVariance.minCoeff() >=
361 -1e-12 * std::max(1., scale),
362 "Gaussian posterior variance is negative");
363 const V diagonal = predicted.gradientVariance.cwiseMax(0.);
364 result.push_back(
365 {std::max(0., predicted.energyVariance),
366 (diagonal.array() / metric_.roots().array().square()).sum(),
367 diagonal.sum()});
368 }
369 return result;
370 }
371 std::size_t observations() const
372 {
373 return points_.size();
374 }
375 std::size_t fittedObservations() const
376 {
377 return fittedSites_;
378 }
379 const std::vector<std::size_t>& fittedArchiveIndices() const noexcept
380 {
381 return fittedOwners_;
382 }
383 std::size_t fitEvaluations() const
384 {
385 return fitEvaluations_;
386 }
388 {
389 return converged_;
390 }
391 double fittedLength() const
392 {
393 return fittedLength_;
394 }
395 Eigen::Index spanDimension() const
396 {
397 return fittedSpan_;
398 }
399 Eigen::Index tangentFactorDimension() const
400 {
401 return fittedTangent_;
402 }
403 Eigen::Index normalFactorDimension() const
404 {
405 return fittedNormal_;
406 }
407};
408} // namespace gpr::quantum
@ x
Definition Enums.h:28
void refitLocal(const std::vector< V > &q, const std::vector< PotentialEvaluation > &values, std::size_t maximumSites)
const std::vector< std::size_t > & fittedArchiveIndices() const noexcept
AffineGaussianArcModel(MassMetric metric, M well, AffineGaussianArcOptions options={})
std::vector< PotentialEvaluation > evaluate(const std::vector< V > &q) const
void refit(const std::vector< V > &q, const std::vector< PotentialEvaluation > &values)
std::vector< PointVariance > posteriorPointVariance(const std::vector< V > &q) const
std::size_t addObservations(const std::vector< V > &q, const std::vector< PotentialEvaluation > &values)
std::function< bool(const V &, V &)> prepareHessian(const V &point) const
Eigen::Index dimension() const noexcept
Models for quantum-path (instanton) searches: arc and tail actions, amplitude continuation.
STL namespace.