Loading...
Searching...
No Matches
NativeGPPath.h
Go to the documentation of this file.
1// SPDX-License-Identifier: MIT
6#pragma once
7#include <algorithm>
8#include <chrono>
9#include <cmath>
10#include <stdexcept>
11
12#include "PotentialPath.h"
13
14namespace gpr::quantum {
15// Native energies and gradients certify every accepted path. The fitted
16// molecular GP supplies only the Newton search curvature; physical Hessians
17// remain owned by the native callback used for fluctuation measurements.
18// The model, metric and this owner must outlive its returned callbacks.
19template <class Model>
21 using V = Eigen::VectorXd;
22 using M = Eigen::MatrixXd;
23 Model& model_;
24 MassMetric metric_;
25 PathPotential native_;
26 std::size_t budget_, reservedHistorySites_;
27 std::vector<V> points_;
28 std::vector<PotentialEvaluation> values_;
29 bool dirty_{}, referenceEnabled_{}, referenceCorrectionValid_{},
30 referencePredictionValid_{};
31 std::size_t referenceRevision_{};
32 PotentialEvaluation referencePrediction_;
33 V referencePhysical_;
34 M referenceHessian_, referenceCorrection_;
35 std::size_t fits_{}, curvatures_{}, referenceCurvatures_{};
36 double fitSeconds_{}, curvatureSeconds_{}, curvaturePreparationSeconds_{},
37 curvatureApplicationSeconds_{};
38 double nativeCallbackSeconds_{}, observationSeconds_{};
39 std::vector<PotentialEvaluation> observe(const std::vector<V>& physical)
40 {
41 const auto begin = std::chrono::steady_clock::now();
42 std::vector<PotentialEvaluation> values;
43 if (native_.evaluateBatch)
44 values = native_.evaluateBatch(physical);
45 else
46 for (const auto& x: physical)
47 values.push_back(native_.evaluate(x));
48 const auto measured = std::chrono::steady_clock::now();
49 nativeCallbackSeconds_ +=
50 std::chrono::duration<double>(measured - begin).count();
51 if (values.size() != physical.size())
52 throw std::runtime_error("Native GP path batch shape differs");
53 std::vector<V> q;
54 std::vector<PotentialEvaluation> weighted;
55 for (std::size_t j = 0; j < physical.size(); ++j) {
56 if (physical[j].size() != metric_.dimension() ||
57 !physical[j].allFinite() || !std::isfinite(values[j].energy) ||
58 values[j].gradient.size() != metric_.dimension() ||
59 !values[j].gradient.allFinite())
60 throw std::runtime_error(
61 "Finite matching native GP path observations required");
62 q.push_back(metric_.weighted(physical[j]));
63 weighted.push_back(
64 {values[j].energy, metric_.gradient(values[j].gradient)});
65 }
66 if (!physical.empty()) {
67 model_.addObservations(q, weighted);
68 points_ = std::move(q);
69 values_ = std::move(weighted);
70 dirty_ = true;
71 }
72 observationSeconds_ += std::chrono::duration<double>(
73 std::chrono::steady_clock::now() - measured)
74 .count();
75 return values;
76 }
77 M gpPhysicalCurvature(const V& physical)
78 {
79 const auto begin = std::chrono::steady_clock::now();
80 auto action = model_.prepareHessian(metric_.weighted(physical));
81 const auto prepared = std::chrono::steady_clock::now();
82 if (!action)
83 throw std::runtime_error(
84 "The molecular GP supplies no search Hessian");
85 const auto d = metric_.dimension();
86 M h(d, d);
87 for (Eigen::Index axis = 0; axis < d; ++axis) {
88 V column;
89 if (!action(V::Unit(d, axis), column) || column.size() != d ||
90 !column.allFinite())
91 throw std::runtime_error("Invalid GP mass-curvature action");
92 h.col(axis) = column;
93 }
94 const auto applied = std::chrono::steady_clock::now();
95 M result = metric_.roots().asDiagonal() * M(.5 * (h + h.transpose())) *
96 metric_.roots().asDiagonal();
97 const auto end = std::chrono::steady_clock::now();
98 ++curvatures_;
99 curvatureSeconds_ += std::chrono::duration<double>(end - begin).count();
100 curvaturePreparationSeconds_ +=
101 std::chrono::duration<double>(prepared - begin).count();
102 curvatureApplicationSeconds_ +=
103 std::chrono::duration<double>(applied - prepared).count();
104 return result;
105 }
106 void ensureFitted()
107 {
108 if (points_.empty())
109 throw std::logic_error(
110 "Native observations must precede GP prediction");
111 if (dirty_) {
112 const auto begin = std::chrono::steady_clock::now();
113 const auto count =
114 std::min(budget_ - reservedHistorySites_, points_.size());
115 std::vector<V> anchors;
116 std::vector<PotentialEvaluation> values;
117 for (std::size_t j = 0; j < count; ++j) {
118 const auto index =
119 count == 1 ? 0 : j * (points_.size() - 1) / (count - 1);
120 anchors.push_back(points_[index]);
121 values.push_back(values_[index]);
122 }
123 model_.refitLocal(anchors, values, budget_);
124 ++fits_;
125 dirty_ = false;
126 referenceCorrectionValid_ = false;
127 referencePredictionValid_ = false;
128 fitSeconds_ += std::chrono::duration<double>(
129 std::chrono::steady_clock::now() - begin)
130 .count();
131 }
132 }
133 M curvature(const V& physical)
134 {
135 ensureFitted();
136 M result = gpPhysicalCurvature(physical);
137 if (referenceEnabled_) {
138 if (!referenceCorrectionValid_) {
139 referenceCorrection_ =
140 referenceHessian_ - gpPhysicalCurvature(referencePhysical_);
141 ++referenceCurvatures_;
142 referenceCorrectionValid_ = true;
143 }
144 result += referenceCorrection_;
145 if (!result.allFinite())
146 throw std::runtime_error(
147 "Nonfinite calibrated search curvature");
148 }
149 return result;
150 }
151
152 void ensureTaylorReference()
153 {
154 ensureFitted();
155 if (!referenceCorrectionValid_) {
156 referenceCorrection_ =
157 referenceHessian_ - gpPhysicalCurvature(referencePhysical_);
158 if (!referenceCorrection_.allFinite())
159 throw std::runtime_error(
160 "Nonfinite Taylor curvature correction");
161 ++referenceCurvatures_;
162 referenceCorrectionValid_ = true;
163 }
164 if (!referencePredictionValid_) {
165 const auto values =
166 model_.evaluate({metric_.weighted(referencePhysical_)});
167 if (values.size() != 1 || !std::isfinite(values[0].energy) ||
168 values[0].gradient.size() != metric_.dimension() ||
169 !values[0].gradient.allFinite())
170 throw std::runtime_error(
171 "Invalid GP Taylor reference prediction");
172 referencePrediction_ = values[0];
173 referencePrediction_.gradient =
174 metric_.roots().cwiseProduct(referencePrediction_.gradient);
175 if (!referencePrediction_.gradient.allFinite())
176 throw std::runtime_error(
177 "Nonfinite physical Taylor reference gradient");
178 referencePredictionValid_ = true;
179 }
180 }
181 std::vector<PotentialEvaluation> taylorValues(
182 const std::vector<V>& physical,
183 const PotentialEvaluation& nativeReferenceValue,
184 std::size_t referenceRevision)
185 {
186 if (physical.empty()) return {};
187 if (referenceRevision != referenceRevision_)
188 throw std::logic_error(
189 "Taylor potential requires its bound reference calibration");
190 std::vector<V> weighted;
191 weighted.reserve(physical.size());
192 for (const auto& point: physical) {
193 if (point.size() != metric_.dimension() || !point.allFinite())
194 throw std::invalid_argument(
195 "Finite matching physical Taylor sites required");
196 weighted.push_back(metric_.weighted(point));
197 }
198 ensureTaylorReference();
199 auto values = model_.evaluate(weighted);
200 if (values.size() != physical.size())
201 throw std::runtime_error("Taylor surrogate batch shape differs");
202 const V gradientCorrection =
203 nativeReferenceValue.gradient - referencePrediction_.gradient;
204 for (std::size_t j = 0; j < values.size(); ++j) {
205 auto& value = values[j];
206 if (!std::isfinite(value.energy) ||
207 value.gradient.size() != metric_.dimension() ||
208 !value.gradient.allFinite())
209 throw std::runtime_error("Invalid GP Taylor prediction");
210 const V delta = physical[j] - referencePhysical_;
211 const V gpGradient = metric_.roots().cwiseProduct(value.gradient);
212 value.energy = nativeReferenceValue.energy +
213 (value.energy - referencePrediction_.energy) +
214 gradientCorrection.dot(delta) +
215 .5 * delta.dot(referenceCorrection_ * delta);
216 value.gradient = nativeReferenceValue.gradient +
217 (gpGradient - referencePrediction_.gradient) +
218 referenceCorrection_ * delta;
219 if (!std::isfinite(value.energy) || !value.gradient.allFinite())
220 throw std::runtime_error(
221 "Nonfinite native Taylor surrogate value");
222 }
223 return values;
224 }
225
226public:
227 // Reserved capacity limits mandatory current-batch anchors. The model
228 // selects the remaining archive sites; their age is not prescribed.
229 NativeGPPath(Model& model, MassMetric metric, PathPotential native,
230 std::size_t fitSites = 24,
231 std::size_t reservedHistorySites = 0)
232 : model_(model),
233 metric_(std::move(metric)),
234 native_(std::move(native)),
235 budget_(fitSites),
236 reservedHistorySites_(reservedHistorySites)
237 {
238 if ((!native_.evaluate && !native_.evaluateBatch) || fitSites < 2 ||
239 reservedHistorySites >= fitSites)
240 throw std::invalid_argument(
241 "Native forces, at least two GP fitting sites and a history "
242 "reserve smaller than the fitting budget required");
243 }
244 // The physical reference calibrates the search matrix:
245 // B(x)=H_native(reference)+H_GP(x)-H_GP(reference). Native energies,
246 // gradients and fluctuation Hessians retain their original ownership.
247 void calibrateSearchCurvature(const V& referencePhysical,
248 const M& nativePhysicalHessian)
249 {
250 const auto d = metric_.dimension();
251 if (referencePhysical.size() != d || !referencePhysical.allFinite() ||
252 nativePhysicalHessian.rows() != d ||
253 nativePhysicalHessian.cols() != d ||
254 !nativePhysicalHessian.allFinite() ||
255 (nativePhysicalHessian - nativePhysicalHessian.transpose()).norm() >
256 1e-12 * std::max(1., nativePhysicalHessian.norm()))
257 throw std::invalid_argument(
258 "Finite physical reference coordinates and a matching "
259 "symmetric native Hessian required");
260 referencePhysical_ = referencePhysical;
261 referenceHessian_ =
262 .5 * (nativePhysicalHessian + nativePhysicalHessian.transpose());
263 referenceEnabled_ = true;
264 referenceCorrectionValid_ = false;
265 referencePredictionValid_ = false;
266 ++referenceRevision_;
267 }
268 // The scalar surrogate shares the calibrated search Hessian and matches
269 // the supplied native energy/gradient at the physical reference. Native
270 // labels and fluctuation Hessians retain their original ownership. Each
271 // returned potential is bound to its installed reference calibration.
273 PotentialEvaluation nativeReferenceValue)
274 {
275 if (!referenceEnabled_ || !std::isfinite(nativeReferenceValue.energy) ||
276 nativeReferenceValue.gradient.size() != metric_.dimension() ||
277 !nativeReferenceValue.gradient.allFinite())
278 throw std::invalid_argument(
279 "Calibrated reference and finite matching physical native "
280 "value required");
281 const auto revision = referenceRevision_;
282 auto result = native_;
283 result.evaluate = [this, nativeReferenceValue, revision](const V& x) {
284 return taylorValues({x}, nativeReferenceValue, revision).at(0);
285 };
286 result.evaluateBatch = [this, nativeReferenceValue,
287 revision](const std::vector<V>& points) {
288 return taylorValues(points, nativeReferenceValue, revision);
289 };
290 result.hessian = {};
291 result.searchHessian = [this, revision](const V& x) {
292 if (revision != referenceRevision_)
293 throw std::logic_error(
294 "Taylor potential requires its bound reference "
295 "calibration");
296 return curvature(x);
297 };
298 return result;
299 }
301 {
302 auto result = native_;
303 result.evaluate = [this](const V& x) { return observe({x}).at(0); };
304 result.evaluateBatch = [this](const auto& x) { return observe(x); };
305 result.searchHessian = [this](const V& x) { return curvature(x); };
306 return result;
307 }
309 {
310 auto result = native_;
311 result.evaluate = [this](const V& x) {
312 ensureFitted();
313 auto value = model_.evaluate({metric_.weighted(x)}).at(0);
314 value.gradient = metric_.roots().cwiseProduct(value.gradient);
315 return value;
316 };
317 result.evaluateBatch = [this](const std::vector<V>& x) {
318 if (x.empty()) return std::vector<PotentialEvaluation>{};
319 ensureFitted();
320 std::vector<V> q;
321 q.reserve(x.size());
322 for (const auto& point: x)
323 q.push_back(metric_.weighted(point));
324 auto values = model_.evaluate(q);
325 for (auto& value: values)
326 value.gradient = metric_.roots().cwiseProduct(value.gradient);
327 return values;
328 };
329 result.hessian = {};
330 result.searchHessian = [this](const V& x) { return curvature(x); };
331 return result;
332 }
333 std::size_t fits() const noexcept
334 {
335 return fits_;
336 }
337 std::size_t searchHessians() const noexcept
338 {
339 return curvatures_;
340 }
341 std::size_t referenceSearchHessians() const noexcept
342 {
343 return referenceCurvatures_;
344 }
345 bool hasSearchCurvatureReference() const noexcept
346 {
347 return referenceEnabled_;
348 }
349 double fitSeconds() const noexcept
350 {
351 return fitSeconds_;
352 }
353 double nativeCallbackSeconds() const noexcept
354 {
355 return nativeCallbackSeconds_;
356 }
357 double observationSeconds() const noexcept
358 {
359 return observationSeconds_;
360 }
361 // Curvature timing excludes refitting and includes the saddle-reference
362 // query when calibration requests one. Preparation and application are
363 // components of the total, not additional disjoint work.
364 double searchCurvatureSeconds() const noexcept
365 {
366 return curvatureSeconds_;
367 }
368 double curvaturePreparationSeconds() const noexcept
369 {
370 return curvaturePreparationSeconds_;
371 }
372 double curvatureApplicationSeconds() const noexcept
373 {
374 return curvatureApplicationSeconds_;
375 }
376};
377} // namespace gpr::quantum
@ x
Definition Enums.h:28
double fitSeconds() const noexcept
double observationSeconds() const noexcept
std::size_t referenceSearchHessians() const noexcept
std::size_t fits() const noexcept
std::size_t searchHessians() const noexcept
double nativeCallbackSeconds() const noexcept
PathPotential taylorSurrogatePotential(PotentialEvaluation nativeReferenceValue)
NativeGPPath(Model &model, MassMetric metric, PathPotential native, std::size_t fitSites=24, std::size_t reservedHistorySites=0)
bool hasSearchCurvatureReference() const noexcept
double curvaturePreparationSeconds() const noexcept
double curvatureApplicationSeconds() const noexcept
PathPotential surrogatePotential()
double searchCurvatureSeconds() const noexcept
void calibrateSearchCurvature(const V &referencePhysical, const M &nativePhysicalHessian)
Models for quantum-path (instanton) searches: arc and tail actions, amplitude continuation.
STL namespace.
std::function< PotentialEvaluation(const Eigen::VectorXd &)> evaluate