Loading...
Searching...
No Matches
TrustRadius.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 "TrustRadius.h"
6
7#include <algorithm>
8#include <cmath>
9#include <limits>
10#include <map>
11
13
14namespace gpr {
15
17{
18 R_train_ = R_train;
19}
20
22{
23 atoms_config_ = atoms_config;
24 has_atoms_config_ = true;
25}
26
28{
29 metric_ = metric;
30 use_atomic_metric_ = true;
31}
32
33double TrustRadius::distanceToTraining(const Eigen::VectorXd& x_new) const
34{
35 const int n = static_cast<int>(R_train_.rows());
36 if (n == 0) {
37 return std::numeric_limits<double>::infinity();
38 }
39
40 if (use_atomic_metric_) {
41 if (!has_atoms_config_) {
42 return std::numeric_limits<double>::infinity();
43 }
44
45 Coord query(1, x_new.size());
46 query.row(0) = x_new.transpose();
47
48 FieldMatrixd dist;
49 aux::Distance distance;
50 switch (metric_) {
52 distance.dist_max1Dlog(query, R_train_, atoms_config_, dist);
53 break;
55 distance.dist_rmsd(query, R_train_, atoms_config_, dist);
56 break;
58 distance.dist_emd(query, R_train_, atoms_config_, dist);
59 break;
60 }
61 if (dist.size() == 0) {
62 return std::numeric_limits<double>::infinity();
63 }
64 return dist.minCoeff();
65 }
66
67 double min_dist = std::numeric_limits<double>::infinity();
68 for (int i = 0; i < n; ++i) {
69 double d = (R_train_.row(i).transpose() - x_new).norm();
70 if (d < min_dist) {
71 min_dist = d;
72 }
73 }
74 return min_dist;
75}
76
77std::vector<int> TrustRadius::kNearestIndices(const Eigen::VectorXd& x_new,
78 int k) const
79{
80 const int n = static_cast<int>(R_train_.rows());
81 std::vector<int> result;
82 if (n == 0 || k <= 0) {
83 return result;
84 }
85
86 std::vector<double> dists(static_cast<size_t>(n),
87 std::numeric_limits<double>::infinity());
88 bool dists_filled = false;
89
90 if (use_atomic_metric_ && has_atoms_config_) {
91 Coord query(1, x_new.size());
92 query.row(0) = x_new.transpose();
93
94 FieldMatrixd dist;
95 aux::Distance distance;
96 switch (metric_) {
98 distance.dist_max1Dlog(query, R_train_, atoms_config_, dist);
99 break;
101 distance.dist_rmsd(query, R_train_, atoms_config_, dist);
102 break;
104 distance.dist_emd(query, R_train_, atoms_config_, dist);
105 break;
106 }
107 if (static_cast<int>(dist.size()) == n) {
108 for (int i = 0; i < n; ++i) {
109 dists[static_cast<size_t>(i)] = *(dist.data() + i);
110 }
111 dists_filled = true;
112 }
113 }
114
115 if (!dists_filled) {
116 // No atomic metric, or the distance backend returned no rows:
117 // rank by the Euclidean vector norm, mirroring distanceToTraining.
118 for (int i = 0; i < n; ++i) {
119 dists[static_cast<size_t>(i)] =
120 (R_train_.row(i).transpose() - x_new).norm();
121 }
122 }
123
124 result.resize(static_cast<size_t>(n));
125 for (int i = 0; i < n; ++i) {
126 result[static_cast<size_t>(i)] = i;
127 }
128 const int kk = std::min(k, n);
129 std::partial_sort(result.begin(), result.begin() + kk, result.end(),
130 [&](int a, int b) {
131 return dists[static_cast<size_t>(a)] <
132 dists[static_cast<size_t>(b)];
133 });
134 result.resize(static_cast<size_t>(kk));
135 // Sort ascending by index so the result is a stable set: callers
136 // compare it against a cached selection to decide whether the
137 // neighbourhood membership actually turned over.
138 std::sort(result.begin(), result.end());
139 return result;
140}
141
142double TrustRadius::emdLipschitzRate(const Eigen::VectorXd& step) const
143{
144 const gpr::FieldMatrixIdx& types = atoms_config_.atoms_mov.type;
145 const Eigen::Index num_atoms = step.size() / 3;
146 if (step.size() % 3 != 0 || types.size() != num_atoms || num_atoms == 0) {
147 // Type index does not line up with the step size: fall back to the
148 // whole-vector norm, a valid (looser) upper bound of the per-type
149 // averaged rate.
150 return step.norm();
151 }
152
153 std::map<gpr::Index_t, double> sum_by_type;
154 std::map<gpr::Index_t, int> count_by_type;
155 for (Eigen::Index i = 0; i < num_atoms; ++i) {
156 const double atom_step = step.segment(3 * i, 3).norm();
157 const gpr::Index_t type = types(0, i);
158 sum_by_type[type] += atom_step;
159 count_by_type[type] += 1;
160 }
161
162 double rate = 0.0;
163 for (const auto& [type, sum]: sum_by_type) {
164 rate = std::max(rate, sum / count_by_type[type]);
165 }
166 return rate;
167}
168
169double TrustRadius::certifiedLineStep(const Eigen::VectorXd& x_from,
170 const Eigen::VectorXd& x_to,
171 double radius) const
172{
173 if (!(radius >= 0.0) || !std::isfinite(radius)) return 0.0;
174 if (x_from.size() != x_to.size() || x_from.size() == 0) return 0.0;
175
176 if (use_atomic_metric_ && has_atoms_config_ &&
177 metric_ != DistanceMetricType::EMD) {
178 // The Lipschitz rate above is derived for EMD (and the plain
179 // Euclidean fallback); RMSD/MAX_1D_LOG are not covered, so refuse
180 // to certify rather than ship an unverified bound.
181 return 0.0;
182 }
183
184 const double d_from = distanceToTraining(x_from);
185 if (!std::isfinite(d_from)) return 0.0;
186
187 const Eigen::VectorXd step = x_to - x_from;
188 const double rate = (use_atomic_metric_ && has_atoms_config_)
189 ? emdLipschitzRate(step)
190 : step.norm();
191 if (rate <= 0.0) {
192 return d_from <= radius ? 1.0 : 0.0;
193 }
194 return std::clamp((radius - d_from) / rate, 0.0, 1.0);
195}
196
197bool TrustRadius::isWithinTrust(const Eigen::VectorXd& x_new,
198 double radius) const
199{
200 return distanceToTraining(x_new) <= radius;
201}
202
203bool TrustRadius::projectLineToTrustBoundary(const Eigen::VectorXd& x_current,
204 const Eigen::VectorXd& x_trial,
205 double radius,
206 Eigen::VectorXd& x_projected) const
207{
208 x_projected = x_trial;
209 if (!(radius >= 0.0) || !std::isfinite(radius)) return false;
210 if (x_current.size() != x_trial.size()) {
211 x_projected = x_current;
212 return false;
213 }
214
215 const double trial_distance = distanceToTraining(x_trial);
216 if (!std::isfinite(trial_distance) || trial_distance <= radius) {
217 return false;
218 }
219
220 const double current_distance = distanceToTraining(x_current);
221 if (!std::isfinite(current_distance) || current_distance > radius) {
222 x_projected = x_current;
223 return false;
224 }
225
226 const Eigen::VectorXd step = x_trial - x_current;
227 if (step.squaredNorm() == 0.0) {
228 x_projected = x_current;
229 return false;
230 }
231
232 auto project_by_bisection = [&](const double upper_alpha) {
233 double lo = 0.0;
234 double hi = upper_alpha;
235 for (int iter = 0; iter < std::numeric_limits<double>::digits; ++iter) {
236 const double alpha = 0.5 * (lo + hi);
237 const Eigen::VectorXd candidate = x_current + alpha * step;
238 const double candidate_distance = distanceToTraining(candidate);
239 if (std::isfinite(candidate_distance) &&
240 candidate_distance <= radius) {
241 lo = alpha;
242 } else {
243 hi = alpha;
244 }
245 }
246 x_projected = x_current + lo * step;
247 };
248
249 const bool rate_established =
250 !use_atomic_metric_ ||
251 (has_atoms_config_ && metric_ == DistanceMetricType::EMD);
252 if (rate_established) {
253 double alpha = certifiedLineStep(x_current, x_trial, radius);
254 if (alpha > 0.0) alpha = std::nextafter(alpha, 0.0);
255 x_projected = x_current + alpha * step;
256 const double projected_distance = distanceToTraining(x_projected);
257 if (!std::isfinite(projected_distance) || projected_distance > radius) {
258 project_by_bisection(alpha);
259 }
260 return true;
261 }
262
263 // RMSD/MAX_1D_LOG: no closed-form Lipschitz rate is established for
264 // these metrics, so fall back to bisection. The count is tied to the
265 // mantissa width of double precision and is therefore deterministic
266 // without a tunable tolerance.
267 project_by_bisection(1.0);
268 return true;
269}
270
271} // namespace gpr
DistanceMetricType
Definition Enums.h:46
Trust radius for GP surrogate validity.
Methods to calculate distances between atoms.
Definition Distance.h:154
void dist_max1Dlog(const gpr::Coord &x1, const gpr::Coord &x2, const gpr::AtomsConfiguration &conf_info, gpr::FieldMatrixd &dist)
Give the maximum difference in the logarithmic inter-atomic distances between atomic configurations C...
Definition Distance.cpp:462
void dist_emd(const gpr::Coord &x1, const gpr::Coord &x2, const gpr::AtomsConfiguration &conf_info, gpr::FieldMatrixd &dist)
Calculates the Earth Mover's Distance between sets of configurations.
void dist_rmsd(const gpr::Coord &x1, const gpr::Coord &x2, const gpr::AtomsConfiguration &conf_info, gpr::FieldMatrixd &dist)
Calculates the aligned Root Mean Square Deviation (RMSD) between sets of configurations.
Definition Distance.cpp:410
bool isWithinTrust(const Eigen::VectorXd &x_new, double radius) const
Check whether x_new is within the trust radius of training data.
double distanceToTraining(const Eigen::VectorXd &x_new) const
Minimum Euclidean distance from x_new to any training point.
std::vector< int > kNearestIndices(const Eigen::VectorXd &x_new, int k) const
Indices of the k training points nearest to x_new.
void setDistanceMetric(DistanceMetricType metric)
Select the atomic distance metric for trust checks.
double certifiedLineStep(const Eigen::VectorXd &x_from, const Eigen::VectorXd &x_to, double radius) const
Largest certified fraction of the segment x_from -> x_to that stays within the trust radius,...
bool projectLineToTrustBoundary(const Eigen::VectorXd &x_current, const Eigen::VectorXd &x_trial, double radius, Eigen::VectorXd &x_projected) const
Project a trial point along a line segment to the trust boundary.
void setTrainingData(const EigenMatrix &R_train)
Store training positions for distance queries.
void setAtomsConfiguration(const AtomsConfiguration &atoms_config)
Store atomic metadata for permutation-aware distance metrics.
Gaussian-process regression, kernels, priors, and the searches that run on the surrogate.
Definition Macros.h:16
Eigen::Matrix< Index_t, EigenDynamic, EigenDynamic, FieldMatrixStorage > FieldMatrixIdx
Definition Macros.h:29
FieldMatrixd Coord
Definition Macros.h:35
uint32_t Index_t
Definition Macros.h:17
Eigen::Matrix< double, EigenDynamic, EigenDynamic, EigenMatrixStorage > EigenMatrix
Definition Macros.h:20
Eigen::Matrix< double, EigenDynamic, EigenDynamic, FieldMatrixStorage > FieldMatrixd
Definition Macros.h:25
Stores configurations of all atoms in the system.
Definition Structures.h:832
AtomsPositionAndType atoms_mov
Info on moving atoms.
Definition Structures.h:844