Loading...
Searching...
No Matches
LazyPotentialOracle.h
Go to the documentation of this file.
1// SPDX-License-Identifier: MIT
2// Copyright (c) gpridge developers
3// See LICENSE for details.
4
5#ifndef GPR_NEB_LAZYPOTENTIALORACLE_H_
6#define GPR_NEB_LAZYPOTENTIALORACLE_H_
7
8#include <Eigen/Dense>
9#include <algorithm>
10#include <array>
11#include <chrono>
12#include <cmath>
13#include <functional>
14#include <memory>
15#include <stdexcept>
16#include <utility>
17#include <vector>
18
19#include "GPNEB.h"
21
22namespace gpr {
23namespace neb {
24namespace detail {
25
26inline void updateMedianNoiseSample(std::vector<double>& samples, double sample,
27 double* median_out)
28{
29 if (!median_out || !std::isfinite(sample) || sample <= 0.0) return;
30 samples.push_back(sample);
31 std::vector<double> sorted(samples);
32 std::nth_element(sorted.begin(), sorted.begin() + sorted.size() / 2,
33 sorted.end());
34 double median = sorted[sorted.size() / 2];
35 if (sorted.size() % 2 == 0) {
36 const double lo = *std::max_element(sorted.begin(),
37 sorted.begin() + sorted.size() / 2);
38 median = 0.5 * (lo + median);
39 }
40 *median_out = median;
41}
42
48struct LazyPotentialOracleState {
49 LazyPotentialOracleState(
50 std::function<pot::PotentialWrapper()> factory_in,
51 std::vector<int> atomic_numbers_in, std::array<double, 9> box_in,
52 int& oracle_call_counter_in, double* oracle_seconds_in = nullptr,
53 double* oracle_energy_noise_rms_in = nullptr,
54 const bool* oracle_variance_updates_enabled_in = nullptr,
55 double* oracle_force_noise_rms_in = nullptr,
56 std::shared_ptr<const gpr::WallClockLimit> wall_clock_limit_in =
57 nullptr)
58 : factory(std::move(factory_in)),
59 atomic_numbers(std::move(atomic_numbers_in)),
60 box(box_in),
61 oracle_call_counter(oracle_call_counter_in),
62 oracle_seconds(oracle_seconds_in),
63 oracle_energy_noise_rms(oracle_energy_noise_rms_in),
64 oracle_variance_updates_enabled(oracle_variance_updates_enabled_in),
65 oracle_force_noise_rms(oracle_force_noise_rms_in),
66 wall_clock_limit(std::move(wall_clock_limit_in))
67 {
68 if (!factory) {
69 throw std::invalid_argument(
70 "lazy potential oracle requires a potential factory");
71 }
72 }
73
74 std::function<pot::PotentialWrapper()> factory;
75 std::unique_ptr<pot::PotentialWrapper> potential;
76 std::vector<int> atomic_numbers;
77 std::array<double, 9> box{};
78 int& oracle_call_counter;
79 double* oracle_seconds = nullptr;
80 double* oracle_energy_noise_rms = nullptr;
81 const bool* oracle_variance_updates_enabled = nullptr;
82 double* oracle_force_noise_rms = nullptr;
83 std::shared_ptr<const gpr::WallClockLimit> wall_clock_limit;
84 std::vector<double> energy_noise_samples;
85 std::vector<double> force_noise_samples;
86
87 pot::PotentialWrapper& wrapped()
88 {
89 gpr::requireWallClock(wall_clock_limit);
90 if (!potential) {
91 potential = std::make_unique<pot::PotentialWrapper>(factory());
92 }
93 return *potential;
94 }
95
101 std::vector<std::pair<double, Eigen::VectorXd>> evaluate(
102 const std::vector<Eigen::VectorXd>& points)
103 {
104 const long n_atoms = static_cast<long>(atomic_numbers.size());
105 const std::size_t B = points.size();
106 std::vector<std::pair<double, Eigen::VectorXd>> out(B);
107 if (B == 0) return out;
108 gpr::requireWallClock(wall_clock_limit);
109 for (const Eigen::VectorXd& point: points) {
110 if (point.size() != 3 * n_atoms) {
111 throw std::runtime_error(
112 "oracle: positions size mismatch with atom count");
113 }
114 }
115 pot::PotentialWrapper& wrapper = wrapped();
116 const auto stride = static_cast<std::size_t>(3 * n_atoms);
117 std::vector<double> energy_noise(B, 0.0);
118 std::vector<double> force_noise(B, 0.0);
119 struct OracleTimer {
120 double* seconds;
121 std::chrono::steady_clock::time_point start =
122 std::chrono::steady_clock::now();
123 ~OracleTimer()
124 {
125 if (seconds) {
126 *seconds += std::chrono::duration<double>(
127 std::chrono::steady_clock::now() - start)
128 .count();
129 }
130 }
131 } timer{oracle_seconds};
132 // Adds the change of the process count over its lifetime to the
133 // caller's counter, on a return and on an exception alike: a point
134 // the potential refused was still attempted.
135 struct CountedCalls {
136 int& counter;
137 long before = pot::oracleEvaluations();
138 ~CountedCalls()
139 {
140 counter += static_cast<int>(pot::oracleEvaluations() - before);
141 }
142 };
143 if (B > 1 && wrapper.hasForceBatchWithUncertainty()) {
144 std::vector<double> R(B * stride);
145 std::vector<double> F(R.size(), 0.0);
146 std::vector<double> U(B, 0.0);
147 for (std::size_t b = 0; b < B; ++b) {
148 std::copy(points[b].data(), points[b].data() + stride,
149 R.data() + b * stride);
150 }
151 // A native batch cannot report which points it attempted on
152 // failure, so the submitted group counts in full. The count
153 // itself lives on the potential, for the whole run.
154 gpr::requireWallClock(wall_clock_limit);
155 {
156 const CountedCalls counted{oracle_call_counter};
158 n_atoms, B, R.data(), atomic_numbers.data(), F.data(),
159 U.data(), energy_noise.data(), force_noise.data(),
160 box.data());
161 }
162 for (std::size_t b = 0; b < B; ++b) {
163 out[b].first = U[b];
164 out[b].second = -Eigen::Map<const Eigen::VectorXd>(
165 F.data() + b * stride, 3 * n_atoms);
166 }
167 } else {
168 for (std::size_t b = 0; b < B; ++b) {
169 gpr::requireWallClock(wall_clock_limit);
170 Eigen::VectorXd forces =
171 Eigen::VectorXd::Zero(points[b].size());
172 double energy = 0.0;
173 {
174 const CountedCalls counted{oracle_call_counter};
175 wrapper.forceWithUncertainty(
176 n_atoms, points[b].data(), atomic_numbers.data(),
177 forces.data(), &energy, &energy_noise[b],
178 &force_noise[b], box.data());
179 }
180 out[b] = {energy, -forces};
181 }
182 }
183 const bool record_variance = !oracle_variance_updates_enabled ||
184 *oracle_variance_updates_enabled;
185 if (record_variance) {
186 // Median, not mean: the model-noise floor should describe the
187 // majority region the surrogate actually works in. A minority
188 // of wall-region calls carries eV-scale model uncertainty
189 // (repulsive geometries on the initial interpolated band), and
190 // a running mean lets that heavy tail set the floor for the
191 // whole run -- the saddle-region data, where the model is
192 // confident to ~1e-3 eV, then swims in a fake noise bath and
193 // the likelihood smooths the fit flat.
194 for (std::size_t b = 0; b < B; ++b) {
195 updateMedianNoiseSample(energy_noise_samples, energy_noise[b],
196 oracle_energy_noise_rms);
197 updateMedianNoiseSample(force_noise_samples, force_noise[b],
198 oracle_force_noise_rms);
199 }
200 }
201 return out;
202 }
203};
204
205} // namespace detail
206
212 std::function<pot::PotentialWrapper()> potential_factory,
213 std::vector<int> atomic_numbers, std::array<double, 9> box,
214 int& oracle_call_counter, double* oracle_seconds = nullptr,
215 double* oracle_energy_noise_rms = nullptr,
216 const bool* oracle_variance_updates_enabled = nullptr,
217 double* oracle_force_noise_rms = nullptr,
218 std::shared_ptr<detail::LazyPotentialOracleState>* state_out = nullptr,
219 std::shared_ptr<const gpr::WallClockLimit> wall_clock_limit = nullptr)
220{
221 auto state = std::make_shared<detail::LazyPotentialOracleState>(
222 std::move(potential_factory), std::move(atomic_numbers), box,
223 oracle_call_counter, oracle_seconds, oracle_energy_noise_rms,
224 oracle_variance_updates_enabled, oracle_force_noise_rms,
225 std::move(wall_clock_limit));
226 if (state_out) *state_out = state;
227 return [state](const Eigen::VectorXd& positions)
228 -> std::pair<double, Eigen::VectorXd> {
229 return state->evaluate({positions}).front();
230 };
231}
232
238 std::shared_ptr<detail::LazyPotentialOracleState> state)
239{
240 if (!state) {
241 throw std::invalid_argument(
242 "lazy potential batch oracle requires the single oracle's state");
243 }
244 return
245 [state = std::move(state)](const std::vector<Eigen::VectorXd>& points)
246 -> std::vector<std::pair<double, Eigen::VectorXd>> {
247 return state->evaluate(points);
248 };
249}
250
251} // namespace neb
252} // namespace gpr
253
254#endif // GPR_NEB_LAZYPOTENTIALORACLE_H_
GP-accelerated NEB: AIE and OIE variants.
Type-erased wrapper around any potential that provides a force() interface.
void forceBatchWithUncertainty(long N, std::size_t B, const double *R, const int *atomicNrs, double *F, double *U, double *energy_noise, double *force_noise, const double *box)
bool hasForceBatchWithUncertainty() const noexcept
void forceWithUncertainty(long N, const double *R, const int *atomicNrs, double *F, double *U, double *energy_noise_rms, double *force_noise_rms, const double *box)
eon_relax_band_t eon_relax_surface_fn void eon_relax_outcome_t * out
The nudged elastic band: path, GP-NEB driver, configuration and result, acquisition,...
std::function< std::vector< std::pair< double, Eigen::VectorXd > >( const std::vector< Eigen::VectorXd > &positions)> NEBBatchOracle
Definition GPNEB.h:89
std::function< std::pair< double, Eigen::VectorXd >( const Eigen::VectorXd &positions)> NEBOracle
Oracle function: positions -> (energy, gradient).
Definition GPNEB.h:82
NEBBatchOracle makeLazyPotentialBatchOracle(std::shared_ptr< detail::LazyPotentialOracleState > state)
NEBOracle makeLazyPotentialOracle(std::function< pot::PotentialWrapper()> potential_factory, std::vector< int > atomic_numbers, std::array< double, 9 > box, int &oracle_call_counter, double *oracle_seconds=nullptr, double *oracle_energy_noise_rms=nullptr, const bool *oracle_variance_updates_enabled=nullptr, double *oracle_force_noise_rms=nullptr, std::shared_ptr< detail::LazyPotentialOracleState > *state_out=nullptr, std::shared_ptr< const gpr::WallClockLimit > wall_clock_limit=nullptr)
Gaussian-process regression, kernels, priors, and the searches that run on the surrogate.
Definition Macros.h:16
void requireWallClock(const std::shared_ptr< const WallClockLimit > &limit)
Definition PhaseTimers.h:73
long oracleEvaluations() noexcept