Loading...
Searching...
No Matches
GprMeanPotential.cpp
Go to the documentation of this file.
1// SPDX-License-Identifier: MIT
2// Copyright (c) gpridge developers
3// See LICENSE for details.
4
5#include "GprMeanPotential.h"
6
7#include <algorithm>
8#include <cmath>
9#include <optional>
10#include <stdexcept>
11#include <string>
12#include <utility>
13
15#include "gpr/neb/Session.h"
17
18namespace pot {
19
21 : rgpot::Potential<GprMeanPotential>(rgpot::PotType::UNKNOWN),
22 model_(&model)
23{
24}
25
27 std::shared_ptr<gpr::GaussianProcessRegression> model)
28 : rgpot::Potential<GprMeanPotential>(rgpot::PotType::UNKNOWN)
29{
30 resetModel(std::move(model));
31}
32
34 : rgpot::Potential<GprMeanPotential>(rgpot::PotType::UNKNOWN),
35 model_(&session.gp),
36 session_(&session)
37{
38}
39
41 std::shared_ptr<gpr::GaussianProcessRegression> model)
42{
43 if (!model)
44 throw std::invalid_argument("GprMeanPotential::resetModel: null model");
45 const bool had_source = model_ != nullptr || session_ != nullptr;
46 const std::uint64_t previous = surfaceEpoch();
47 owned_model_ = std::move(model);
48 model_ = owned_model_.get();
49 session_ = nullptr;
50 base_factor_epoch_ = model_->factorEpoch();
51 epoch_base_ = had_source ? (previous + 1)
52 : std::max<std::uint64_t>(1, base_factor_epoch_);
53}
54
55gpr::GaussianProcessRegression& GprMeanPotential::model()
56{
57 if (model_ == nullptr) throw std::logic_error("GprMeanPotential: no model");
58 return *model_;
59}
60
61const gpr::GaussianProcessRegression& GprMeanPotential::model() const
62{
63 if (model_ == nullptr) throw std::logic_error("GprMeanPotential: no model");
64 return *model_;
65}
66
67std::uint64_t GprMeanPotential::surfaceEpoch() const noexcept
68{
69 if (session_ != nullptr) return session_->surfaceEpoch();
70 if (model_ != nullptr) {
71 const std::uint64_t factor = model_->factorEpoch();
72 const std::uint64_t delta = factor - base_factor_epoch_;
73 return epoch_base_ + delta;
74 }
75 return 0;
76}
77
78std::uint64_t GprMeanPotential::paramsKey() const noexcept
79{
80 return surfaceEpoch();
81}
82
83rgpot::PotCaps GprMeanPotential::caps() const noexcept
84{
85 return {.reentrancy = rgpot::Reentrancy::ProcessSerial, .periodic = true};
86}
87
88void GprMeanPotential::forceImpl(const rgpot::ForceInput& in,
89 rgpot::ForceOut* out) const
90{
91 if (in.nAtoms == 0 || in.pos == nullptr || out == nullptr ||
92 out->F == nullptr)
93 throw std::invalid_argument(
94 "GprMeanPotential::forceImpl: null input or output");
95 const_cast<GprMeanPotential*>(this)->force(
96 static_cast<long>(in.nAtoms), in.pos, in.atmnrs, out->F, &out->energy,
97 &out->variance, in.box);
98}
99
100void GprMeanPotential::hessianVectorImpl(const rgpot::ForceInput& in,
101 const double* direction,
102 double* action) const
103{
104 if (in.nAtoms == 0 || in.pos == nullptr || direction == nullptr ||
105 action == nullptr)
106 throw std::invalid_argument(
107 "GprMeanPotential::hessianVectorImpl: null input");
108 validateSystem(static_cast<long>(in.nAtoms), in.atmnrs, in.box,
109 "hessianVectorImpl");
110 const auto n = static_cast<Eigen::Index>(3 * in.nAtoms);
111 gpr::Coord positions(1, n);
112 for (Eigen::Index i = 0; i < n; ++i)
113 positions(0, i) = in.pos[i];
114 const Eigen::Map<const Eigen::VectorXd> vector(direction, n);
115 // The prepared operator owns an exact refusal. The dispatched product
116 // would replace that refusal with a finite-difference stencil. Energy
117 // and gradient acquire the global model first; the action does the
118 // same, so a parked or stale factor is not the answer.
119 std::optional<gpr::neb::ActiveLearningSession::ModelLease> lease;
120 auto& posterior = [this, &lease]() -> gpr::GaussianProcessRegression& {
121 if (session_ == nullptr)
122 return const_cast<GprMeanPotential*>(this)->model();
123 lease.emplace(session_->acquireGlobalModel());
124 return lease->gp();
125 }();
126 const auto apply = posterior.prepareMeanHessian(positions);
127 Eigen::VectorXd result;
128 if (!apply || !apply(vector, result) || result.size() != n)
129 throw std::runtime_error("GP Hessian action is unavailable");
130 std::copy_n(result.data(), n, action);
131}
132
133void GprMeanPotential::validateSystem(long N, const int* atomicNrs,
134 const double* box,
135 const char* caller) const
136{
137 const auto& config = model().getAtomsConfig();
138 const std::string prefix =
139 "GprMeanPotential::" + std::string(caller) + ": ";
140 if (atomicNrs == nullptr || box == nullptr)
141 throw std::invalid_argument(prefix +
142 "atomic numbers or cell do not match GP");
143 // A loaded configuration stores one atomic number and one mobility flag
144 // per atom, frozen ones included. The query and the eOn callback pass
145 // only the moving atoms, so the expected species are the moving entries.
146 const auto species_n = config.atomicNrs.size();
147 const bool full_system =
148 species_n > 0 && config.is_frozen.size() == species_n;
149 if (!full_system) {
150 if (species_n != N)
151 throw std::invalid_argument(
152 prefix + "atomic numbers or cell do not match GP");
153 for (long atom = 0; atom < N; ++atom) {
154 if (atomicNrs[atom] != config.atomicNrs(0, atom))
155 throw std::invalid_argument(prefix +
156 "atomic numbers do not match GP");
157 }
158 } else {
159 long moving = 0;
160 for (Eigen::Index atom = 0; atom < species_n; ++atom) {
161 if (config.is_frozen(0, atom) != MOVING_ATOM) continue;
162 if (moving >= N || atomicNrs[moving] != config.atomicNrs(0, atom))
163 throw std::invalid_argument(prefix +
164 "atomic numbers do not match GP");
165 ++moving;
166 }
167 if (moving != N)
168 throw std::invalid_argument(
169 prefix + "atomic numbers or cell do not match GP");
170 }
171 constexpr double kCellRtol = 1.0e-12;
172 // Periodicity is the stored cell: initialize() zeros open axes, and a
173 // nonzero row is a periodic lattice vector. Scale the tolerance by those
174 // rows only. A longer vacuum vector must not widen it, and a cell with
175 // no periodic row has nothing to compare.
176 const auto periodic = gpr::geometry::cellPeriodicAxes(config.cell);
177 double cell_scale = 1.0;
178 bool any_periodic = false;
179 for (int row = 0; row < 3; ++row) {
180 if (!periodic[static_cast<std::size_t>(row)]) continue;
181 any_periodic = true;
182 for (int col = 0; col < 3; ++col) {
183 const int entry = 3 * row + col;
184 cell_scale = std::max(cell_scale, std::abs(config.cell[entry]));
185 }
186 }
187 if (!any_periodic) return;
188 const double cell_atol = kCellRtol * cell_scale;
189 for (int row = 0; row < 3; ++row) {
190 if (!periodic[static_cast<std::size_t>(row)]) continue;
191 for (int col = 0; col < 3; ++col) {
192 const int entry = 3 * row + col;
193 if (!(std::abs(box[entry] - config.cell[entry]) <= cell_atol))
194 throw std::invalid_argument(prefix + "cell does not match GP");
195 }
196 }
197}
198
199void GprMeanPotential::force(long N, const double* R, const int* atomicNrs,
200 double* F, double* U, double* variance,
201 const double* box)
202{
203 if (N <= 0 || R == nullptr || F == nullptr || U == nullptr)
204 throw std::invalid_argument("GprMeanPotential::force: null input");
205 validateSystem(N, atomicNrs, box, "force");
206 gpr::Observation query;
207 query.R.resize(1, 3 * N);
208 for (long i = 0; i < 3 * N; ++i)
209 query.R(0, i) = R[i];
210 if (session_ != nullptr)
211 session_->predictAtImage(-1, query);
212 else
213 model().calculatePotentialDispatched(query);
214 *U = (query.E.size() > 0) ? query.E(0, 0) : 0.0;
215 if (query.G.rows() > 0 && query.G.cols() == 3 * N) {
216 for (long i = 0; i < 3 * N; ++i)
217 F[i] = -query.G(0, i);
218 } else {
219 for (long i = 0; i < 3 * N; ++i)
220 F[i] = 0.0;
221 }
222 if (variance != nullptr) {
223 Eigen::RowVectorXd gate;
224 if (model().tryGateEnergyVariance(query, gate) && gate.size() > 0)
225 *variance = gate(0);
226 else {
227 model().calculateVarianceDispatched(query);
228 *variance = (query.E.size() > 0) ? query.E(0, 0) : 0.0;
229 }
230 }
231}
232
233void GprMeanPotential::forceBatch(long N, std::size_t B, const double* R,
234 const int* atomicNrs, double* F, double* U,
235 const double* box)
236{
237 if (N <= 0 || B == 0 || R == nullptr || F == nullptr || U == nullptr)
238 throw std::invalid_argument("GprMeanPotential::forceBatch: null input");
239 validateSystem(N, atomicNrs, box, "forceBatch");
240 std::vector<gpr::Observation> queries(B);
241 std::vector<gpr::Observation*> ptrs(B, nullptr);
242 for (std::size_t b = 0; b < B; ++b) {
243 queries[b].R.resize(1, 3 * N);
244 for (long i = 0; i < 3 * N; ++i)
245 queries[b].R(0, i) = R[b * static_cast<std::size_t>(3 * N) +
246 static_cast<std::size_t>(i)];
247 ptrs[b] = &queries[b];
248 }
249 model().calculatePotentialBatch(ptrs);
250 for (std::size_t b = 0; b < B; ++b) {
251 U[b] = (queries[b].E.size() > 0) ? queries[b].E(0, 0) : 0.0;
252 if (queries[b].G.rows() > 0 && queries[b].G.cols() == 3 * N) {
253 for (long i = 0; i < 3 * N; ++i)
254 F[b * static_cast<std::size_t>(3 * N) +
255 static_cast<std::size_t>(i)] = -queries[b].G(0, i);
256 } else {
257 for (long i = 0; i < 3 * N; ++i)
258 F[b * static_cast<std::size_t>(3 * N) +
259 static_cast<std::size_t>(i)] = 0.0;
260 }
261 }
262}
263
265{
266 GprMeanPotential* self = this;
267 auto wrapper = PotentialWrapper(
268 [self](long N, const double* R, const int* atomicNrs, double* F,
269 double* U, double* energy_noise_rms, const double* box) {
270 // force() stores energy and forces as it goes. Hold them until
271 // the variance converts, so a throw leaves the caller buffers
272 // untouched. N <= 0 or a null output still hits force()'s own
273 // rejection, which writes nothing.
274 const bool scratch = N > 0 && F != nullptr && U != nullptr;
275 const std::size_t n_coord =
276 scratch ? static_cast<std::size_t>(N) * 3 : 0;
277 std::vector<double> scratch_forces(n_coord);
278 double scratch_energy = 0.0;
279 double variance = 0.0;
280 self->force(N, R, atomicNrs, scratch ? scratch_forces.data() : F,
281 scratch ? &scratch_energy : U,
282 energy_noise_rms != nullptr ? &variance : nullptr, box);
283 const double energy_rms = energy_noise_rms != nullptr
284 ? energyVarianceToRms(variance)
285 : 0.0;
286 if (scratch) {
287 std::copy_n(scratch_forces.data(), n_coord, F);
288 *U = scratch_energy;
289 }
290 if (energy_noise_rms != nullptr) *energy_noise_rms = energy_rms;
291 });
292 wrapper.setForceBatch([self](long N, std::size_t B, const double* R,
293 const int* atomicNrs, double* F, double* U,
294 const double* box) {
295 // The batch predicts means only; the single call carries the
296 // gate variance.
297 self->forceBatch(N, B, R, atomicNrs, F, U, box);
298 });
299 return wrapper;
300}
301
302} // namespace pot
@ MOVING_ATOM
Definition Enums.h:35
ActiveLearningSession: shared GP + training data across GP-NEB and GP-Dimer phases.
MeanHessianAction prepareMeanHessian(const Coord &R)
Linear action of the physical posterior mean at one geometry.
const AtomsConfiguration & getAtomsConfig() const
std::uint64_t paramsKey() const noexcept override
void hessianVectorImpl(const rgpot::ForceInput &in, const double *direction, double *action) const
rgpot::PotCaps caps() const noexcept override
PotentialWrapper asWrapper()
void force(long N, const double *R, const int *atomicNrs, double *F, double *U, double *variance, const double *box)
void resetModel(std::shared_ptr< gpr::GaussianProcessRegression > model)
void forceImpl(const rgpot::ForceInput &in, rgpot::ForceOut *out) const override
std::uint64_t surfaceEpoch() const noexcept
void forceBatch(long N, std::size_t B, const double *R, const int *atomicNrs, double *F, double *U, const double *box)
GprMeanPotential(gpr::GaussianProcessRegression &model)
Type-erased wrapper around any potential that provides a force() interface.
void setForceBatch(ForceBatchFn fn)
eon_relax_band_t eon_relax_surface_fn void eon_relax_outcome_t * out
std::array< bool, 3 > cellPeriodicAxes(const double cell[9]) noexcept
Definition MinImage.h:93
FieldMatrixd Coord
Definition Macros.h:35
Potential wrappers and the batched oracle interface.
double energyVarianceToRms(const double variance)
Observation data: energy, gradient and positions.
FieldMatrixd E