Loading...
Searching...
No Matches
PairSplineModel.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 "PairSplineModel.h"
6
7#include <linkcell.h>
8
9#include <algorithm>
10#include <chrono>
11#include <cmath>
12#include <limits>
13#include <unordered_map>
14
15#if defined(__AVX2__)
16#include <immintrin.h>
17#endif
18
19namespace gpr {
20namespace neb {
21
22namespace {
23
24// Cardinal cubic B-spline on [0, 4) with its first two derivatives.
25inline void cubic(double u, double& b, double& db, double& d2b)
26{
27 if (u < 0.0 || u >= 4.0) {
28 b = db = d2b = 0.0;
29 return;
30 }
31 if (u < 1.0) {
32 b = u * u * u / 6.0;
33 db = 0.5 * u * u;
34 d2b = u;
35 } else if (u < 2.0) {
36 b = (-3.0 * u * u * u + 12.0 * u * u - 12.0 * u + 4.0) / 6.0;
37 db = (-9.0 * u * u + 24.0 * u - 12.0) / 6.0;
38 d2b = (-18.0 * u + 24.0) / 6.0;
39 } else if (u < 3.0) {
40 b = (3.0 * u * u * u - 24.0 * u * u + 60.0 * u - 44.0) / 6.0;
41 db = (9.0 * u * u - 48.0 * u + 60.0) / 6.0;
42 d2b = (18.0 * u - 48.0) / 6.0;
43 } else {
44 const double v = 4.0 - u;
45 b = v * v * v / 6.0;
46 db = -0.5 * v * v;
47 d2b = v;
48 }
49}
50
51} // namespace
52
54 Eigen::VectorXd frozen_positions,
55 const std::array<double, 9>& cell,
56 double r_min, double r_cut, double spacing)
57 : n_moving_(n_moving),
58 frozen_(std::move(frozen_positions)),
59 box_(cell),
60 cell_(cell),
61 r_min_(r_min),
62 r_cut_(r_cut),
63 h_(spacing > 0.0 ? spacing : 0.25)
64{
65 if (!(r_cut_ > r_min_)) r_cut_ = r_min_ + 4.0 * h_;
66 n_basis_ =
67 static_cast<Eigen::Index>(std::floor((r_cut_ - r_min_) / h_)) + 4;
68 const Eigen::Index m = n_basis_ + 1;
69 ete_.setZero(m, m);
70 ety_.setZero(m);
71 gtg_.setZero(n_basis_, n_basis_);
72 gty_.setZero(n_basis_);
73 weights_.setZero(m);
74}
75
76double PairSplineModel::minimumSeparation(const Eigen::VectorXd& x) const
77{
78 double best = std::numeric_limits<double>::infinity();
79 if (x.size() != 3 * n_moving_) return best;
80 const Eigen::Index n_frozen = frozen_.size() / 3;
81 const double* xp = x.data();
82 const double* fp = frozen_.data();
83 auto dist2 = [&](const double* a, const double* b) {
84 return box_.dist2(Eigen::Vector3d(a[0], a[1], a[2]),
85 Eigen::Vector3d(b[0], b[1], b[2]));
86 };
87 for (Eigen::Index i = 0; i < n_moving_; ++i) {
88 for (Eigen::Index j = i + 1; j < n_moving_; ++j)
89 best = std::min(best, dist2(xp + 3 * i, xp + 3 * j));
90 for (Eigen::Index j = 0; j < n_frozen; ++j)
91 best = std::min(best, dist2(xp + 3 * i, fp + 3 * j));
92 }
93 return std::sqrt(best);
94}
95
96void PairSplineModel::setNoise(double energy_sigma, double gradient_sigma)
97{
98 noise_energy_ = std::max(energy_sigma, 1e-8);
99 noise_gradient_ = std::max(gradient_sigma, 1e-8);
100}
101
102void PairSplineModel::setPrior(double weight_sigma, double curvature_sigma)
103{
104 prior_weight_ = std::max(weight_sigma, 1e-8);
105 prior_curvature_ = std::max(curvature_sigma, 1e-8);
106}
107
108void PairSplineModel::setTailSplit(double split, double refresh)
109{
110 split_ = (split > r_min_ && split + skin_ < r_cut_) ? split : 0.0;
111 tail_refresh_ = std::max(refresh, 0.0);
112 for (auto& list: lists_)
113 list.positions.resize(0);
114}
115
117{
118 if (slot >= 0 && static_cast<std::size_t>(slot) < lists_.size())
119 lists_[static_cast<std::size_t>(slot)].tail_fit = -1;
120}
121
122void PairSplineModel::basis(double r, int& first, double* b, double* db,
123 double* d2b) const
124{
125 const double t = (r - r_min_) / h_;
126 const int k0 = static_cast<int>(std::floor(t));
127 first = k0;
128 for (int k = 0; k < 4; ++k) {
129 const int index = first + k;
130 const double u = t - static_cast<double>(index) + 3.0;
131 if (index < 0 || index >= n_basis_) {
132 b[k] = db[k] = d2b[k] = 0.0;
133 continue;
134 }
135 cubic(u, b[k], db[k], d2b[k]);
136 db[k] /= h_;
137 d2b[k] /= h_ * h_;
138 }
139}
140
141void PairSplineModel::tabulate()
142{
143 // On knot interval k the four overlapping cardinal splines sum to one
144 // cubic in v = t - k: c0 + c1 v + c2 v^2 + c3 v^3.
145 const Eigen::Index intervals = std::max<Eigen::Index>(n_basis_ - 3, 0);
146 table_.assign(static_cast<std::size_t>(intervals), {0.0, 0.0, 0.0, 0.0});
147 for (Eigen::Index k = 0; k < intervals; ++k) {
148 const double w0 = weights_(1 + k), w1 = weights_(2 + k),
149 w2 = weights_(3 + k), w3 = weights_(4 + k);
150 auto& c = table_[static_cast<std::size_t>(k)];
151 c[0] = (w0 + 4.0 * w1 + w2) / 6.0;
152 c[1] = (-3.0 * w0 + 3.0 * w2) / 6.0;
153 c[2] = (3.0 * w0 - 6.0 * w1 + 3.0 * w2) / 6.0;
154 c[3] = (-w0 + 3.0 * w1 - 3.0 * w2 + w3) / 6.0;
155 }
156}
157
158inline bool PairSplineModel::lookup(double r, double& phi, double& dphi,
159 double& d2phi) const
160{
161 const double t = (r - r_min_) / h_;
162 const int k = static_cast<int>(t);
163 if (t < 0.0 || k >= static_cast<int>(table_.size())) return false;
164 const double v = t - static_cast<double>(k);
165 const auto& c = table_[static_cast<std::size_t>(k)];
166 phi = c[0] + v * (c[1] + v * (c[2] + v * c[3]));
167 dphi = (c[1] + v * (2.0 * c[2] + 3.0 * c[3] * v)) / h_;
168 d2phi = (2.0 * c[2] + 6.0 * c[3] * v) / (h_ * h_);
169 return true;
170}
171
172void PairSplineModel::radial(double r, double& phi, double& dphi,
173 double& d2phi) const
174{
175 phi = dphi = d2phi = 0.0;
176 if (!ready_ || r < r_min_ || r >= r_cut_) return;
177 (void)lookup(r, phi, dphi, d2phi);
178}
179
180void PairSplineModel::rebuildList(const Eigen::VectorXd& x, List& list) const
181{
182 const auto t0 = std::chrono::steady_clock::now();
183 auto& list_ = list.pairs;
184 const double reach = r_cut_ + skin_;
185 const double reach2 = reach * reach;
186 const Eigen::Index n_frozen = frozen_.size() / 3;
187 const double* xp = x.data();
188 const double* fp = frozen_.data();
189 // Minimum-image separation xi - xj and the lattice shift that realises it.
190 // Kept for a non-periodic cell and as the shift of each linkcell pair:
191 // the stored shift is this difference, so a later xi - xj + shift is the
192 // same floating-point value the direct search produced.
193 auto separation = [&](const double* xi, const double* xj,
194 Eigen::Vector3d& d, Eigen::Vector3d& shift) {
195 const Eigen::Vector3d pi(xi[0], xi[1], xi[2]), pj(xj[0], xj[1], xj[2]);
196 d = box_.displacement(pj, pi);
197 shift = d - (pi - pj);
198 };
199 auto direct_pairs = [&](std::vector<Pair>& out) {
200 Eigen::Vector3d d, shift;
201 for (Eigen::Index i = 0; i < n_moving_; ++i) {
202 const double* xi = xp + 3 * i;
203 for (Eigen::Index j = i + 1; j < n_moving_; ++j) {
204 separation(xi, xp + 3 * j, d, shift);
205 if (d.squaredNorm() > reach2) continue;
206 out.push_back(
207 {static_cast<int>(i), static_cast<int>(j), false, shift});
208 }
209 for (Eigen::Index j = 0; j < n_frozen; ++j) {
210 separation(xi, fp + 3 * j, d, shift);
211 if (d.squaredNorm() > reach2) continue;
212 out.push_back(
213 {static_cast<int>(i), static_cast<int>(j), true, shift});
214 }
215 }
216 };
217 auto cell_pairs = [&](std::vector<Pair>& out) -> bool {
218 if (!box_.periodic() || n_moving_ + n_frozen <= 0) return false;
219 const Eigen::Index n_all = n_moving_ + n_frozen;
220 std::vector<double> xyz(static_cast<std::size_t>(3 * n_all));
221 std::copy(xp, xp + 3 * n_moving_, xyz.begin());
222 if (n_frozen > 0)
223 std::copy(fp, fp + 3 * n_frozen, xyz.begin() + 3 * n_moving_);
224 lc_cell raw{};
225 raw.ax = cell_[0];
226 raw.ay = cell_[1];
227 raw.az = cell_[2];
228 raw.bx = cell_[3];
229 raw.by = cell_[4];
230 raw.bz = cell_[5];
231 raw.cx = cell_[6];
232 raw.cy = cell_[7];
233 raw.cz = cell_[8];
234 const auto axes = box_.periodicAxes();
235 const int pbc[3] = {axes[0] ? 1 : 0, axes[1] ? 1 : 0, axes[2] ? 1 : 0};
236 std::size_t n_found = 0;
237 // A linear buffer covers dilute lists in one call. An undersized
238 // buffer reports the exact count and parks the rows for the retry.
239 std::vector<lc_pair> found(
240 std::max(static_cast<std::size_t>(n_all), out.capacity()));
241 // closed=1 keeps dist^2 <= reach^2, the same cut as the direct loop.
242 int status = lc_pairs_within_pbc(
243 xyz.data(), static_cast<std::size_t>(n_all), &raw, pbc, reach,
244 nullptr, reach, 1, 1, 1, found.data(), found.size(), &n_found);
245 if (status != 0) {
246 if (n_found <= found.size()) return false;
247 found.resize(n_found);
248 status = lc_pairs_within_pbc(
249 xyz.data(), static_cast<std::size_t>(n_all), &raw, pbc, reach,
250 nullptr, reach, 1, 1, 1, found.data(), found.size(), &n_found);
251 if (status != 0) return false;
252 }
253 found.resize(n_found);
254 struct Key {
255 int i;
256 int j;
257 int frozen;
258 double dist2;
259 };
260 std::vector<Key> keys;
261 keys.reserve(found.size());
262 const int nm = static_cast<int>(n_moving_);
263 for (const auto& pair: found) {
264 int i = pair.i;
265 int j = pair.j;
266 if (i >= nm && j >= nm) continue;
267 if (i >= nm || (j < nm && i > j)) std::swap(i, j);
268 const int frozen = j >= nm ? 1 : 0;
269 keys.push_back({i, frozen ? j - nm : j, frozen, pair.dist2});
270 }
271 std::sort(keys.begin(), keys.end(), [](const Key& a, const Key& b) {
272 if (a.i != b.i) return a.i < b.i;
273 if (a.frozen != b.frozen) return a.frozen < b.frozen;
274 if (a.j != b.j) return a.j < b.j;
275 return a.dist2 < b.dist2;
276 });
277 keys.erase(std::unique(keys.begin(), keys.end(),
278 [](const Key& a, const Key& b) {
279 return a.i == b.i && a.j == b.j &&
280 a.frozen == b.frozen;
281 }),
282 keys.end());
283 out.reserve(keys.size());
284 for (const auto& key: keys) {
285 const double* xi = xyz.data() + 3 * key.i;
286 const double* xj =
287 xyz.data() + 3 * (key.frozen ? nm + key.j : key.j);
288 Eigen::Vector3d d, shift;
289 separation(xi, xj, d, shift);
290 if (d.squaredNorm() > reach2) continue;
291 out.push_back({key.i, key.j, key.frozen != 0, shift});
292 }
293 return true;
294 };
295 auto same_pairs = [](const std::vector<Pair>& a,
296 const std::vector<Pair>& b) {
297 if (a.size() != b.size()) return false;
298 for (std::size_t i = 0; i < a.size(); ++i) {
299 if (a[i].i != b[i].i || a[i].j != b[i].j ||
300 a[i].frozen != b[i].frozen)
301 return false;
302 if (a[i].shift != b[i].shift) return false;
303 }
304 return true;
305 };
306 std::vector<int> changed;
307 std::vector<char> moved(static_cast<std::size_t>(n_moving_), 0);
308 if (list_method_ != 0 && list.positions.size() == x.size()) {
309 for (Eigen::Index i = 0; i < n_moving_; ++i) {
310 if (x(3 * i) != list.positions(3 * i) ||
311 x(3 * i + 1) != list.positions(3 * i + 1) ||
312 x(3 * i + 2) != list.positions(3 * i + 2)) {
313 changed.push_back(static_cast<int>(i));
314 moved[static_cast<std::size_t>(i)] = 1;
315 }
316 }
317 }
318 const bool local_update =
319 list.positions.size() == x.size() && list_method_ != 0 &&
320 changed.size() <= static_cast<std::size_t>(n_moving_ / 4);
321 if (local_update) {
322 // Unchanged endpoints retain their exact lattice shift. Only pairs
323 // touching a changed atom need a fresh minimum-image calculation.
324 list_.erase(
325 std::remove_if(list_.begin(), list_.end(),
326 [&](const Pair& p) {
327 return moved[static_cast<std::size_t>(p.i)] ||
328 (!p.frozen &&
329 moved[static_cast<std::size_t>(p.j)]);
330 }),
331 list_.end());
332 auto append = [&](Eigen::Index i, Eigen::Index j, bool frozen) {
333 Eigen::Vector3d d, shift;
334 separation(xp + 3 * i, (frozen ? fp : xp) + 3 * j, d, shift);
335 if (d.squaredNorm() > reach2) return;
336 list_.push_back(
337 {static_cast<int>(i), static_cast<int>(j), frozen, shift});
338 };
339 for (Eigen::Index i = 0; i < n_moving_; ++i) {
340 if (moved[static_cast<std::size_t>(i)]) {
341 for (Eigen::Index j = i + 1; j < n_moving_; ++j)
342 append(i, j, false);
343 for (Eigen::Index j = 0; j < n_frozen; ++j)
344 append(i, j, true);
345 } else {
346 for (int j: changed)
347 if (j > i) append(i, j, false);
348 }
349 }
350 std::sort(list_.begin(), list_.end(), [](const Pair& a, const Pair& b) {
351 if (a.i != b.i) return a.i < b.i;
352 if (a.frozen != b.frozen) return a.frozen < b.frozen;
353 return a.j < b.j;
354 });
355 } else if (list_method_ == 0 && box_.periodic()) {
356 std::vector<Pair> by_cell, by_direct;
357 const bool cells_ok = cell_pairs(by_cell);
358 direct_pairs(by_direct);
359 // A cell edge equal to the search radius bounds the neighbouring
360 // bins in each direction. The cells a search visits fill a cube
361 // of that edge past the cutoff on every side. The direct loop
362 // visits the upper triangle, half the atom pairs, so the cell list
363 // does less work when that cube is smaller than half the periodic
364 // cell. A wall-clock comparison is not a property of the model: it
365 // flips with the log and then keeps a list that later geometries
366 // no longer match.
367 const double edge = reach;
368 const double side = 2.0 * reach + edge;
369 const Eigen::Vector3d axis_a(cell_[0], cell_[1], cell_[2]);
370 const Eigen::Vector3d axis_b(cell_[3], cell_[4], cell_[5]);
371 const Eigen::Vector3d axis_c(cell_[6], cell_[7], cell_[8]);
372 const double volume = std::abs(axis_a.dot(axis_b.cross(axis_c)));
373 const bool cells_cheaper =
374 cells_ok && volume > 0.0 && side * side * side < 0.5 * volume;
375 if (cells_cheaper && same_pairs(by_cell, by_direct)) {
376 list_ = std::move(by_cell);
377 list_method_ = 1;
378 } else {
379 list_ = std::move(by_direct);
380 list_method_ = 2;
381 }
382 } else if (list_method_ == 1) {
383 list_.clear();
384 if (!cell_pairs(list_)) direct_pairs(list_);
385 } else {
386 list_.clear();
387 direct_pairs(list_);
388 }
389 list.positions = x;
390 list.tail_fit = -1;
391 // Flat arrays in two blocks: pairs that can come within the split
392 // radius before the next rebuild, then the tail. Without a split every
393 // pair is a near pair.
394 const std::size_t n_pairs = list_.size();
395 list.oi.resize(n_pairs);
396 list.oj.resize(n_pairs);
397 list.sx.resize(n_pairs);
398 list.sy.resize(n_pairs);
399 list.sz.resize(n_pairs);
400 list.masked.clear();
401 list.masked_atoms.clear();
402 const double near2 = (split_ + skin_) * (split_ + skin_);
403 const int nm3 = static_cast<int>(3 * n_moving_);
404 std::size_t front = 0, back = n_pairs;
405 for (const auto& p: list_) {
406 bool near = true;
407 if (split_ > 0.0) {
408 const double* xi = xp + 3 * p.i;
409 const double* xj = p.frozen ? fp + 3 * p.j : xp + 3 * p.j;
410 const double dx = xi[0] - xj[0] + p.shift[0];
411 const double dy = xi[1] - xj[1] + p.shift[1];
412 const double dz = xi[2] - xj[2] + p.shift[2];
413 near = dx * dx + dy * dy + dz * dz < near2;
414 }
415 const std::size_t k = near ? front++ : --back;
416 list.oi[k] = 3 * p.i;
417 list.oj[k] = p.frozen ? nm3 + 3 * p.j : 3 * p.j;
418 list.sx[k] = p.shift[0];
419 list.sy[k] = p.shift[1];
420 list.sz[k] = p.shift[2];
421 }
422 list.n_near = front;
423 ++list_builds_;
424 list_seconds_ +=
425 std::chrono::duration<double>(std::chrono::steady_clock::now() - t0)
426 .count();
427}
428
429PairSplineModel::List& PairSplineModel::ensureList(const Eigen::VectorXd& x,
430 int slot) const
431{
432 if (slot < 0) slot = 0;
433 if (static_cast<int>(lists_.size()) <= slot)
434 lists_.resize(static_cast<std::size_t>(slot) + 1);
435 List& list = lists_[static_cast<std::size_t>(slot)];
436 if (list.positions.size() == x.size()) {
437 double moved = 0.0;
438 for (Eigen::Index i = 0; i < n_moving_; ++i)
439 moved = std::max(
440 moved, (x.segment<3>(3 * i) - list.positions.segment<3>(3 * i))
441 .norm());
442 if (moved < 0.5 * skin_) return list;
443 }
444 rebuildList(x, list);
445 return list;
446}
447
448bool PairSplineModel::separation(const Pair& p, const Eigen::VectorXd& x,
449 Eigen::Vector3d& d, double& r) const
450{
451 const Eigen::Vector3d xj =
452 p.frozen ? Eigen::Vector3d(frozen_.segment<3>(3 * p.j))
453 : Eigen::Vector3d(x.segment<3>(3 * p.j));
454 d = x.segment<3>(3 * p.i) - xj + p.shift;
455 r = d.norm();
456 return r >= r_min_ && r < r_cut_;
457}
458
459void PairSplineModel::features(const Eigen::VectorXd& x, Eigen::VectorXd& phi,
460 Eigen::MatrixXd& dphi, int slot) const
461{
462 const auto& list_ = ensureList(x, slot).pairs;
463 phi.setZero(n_basis_);
464 dphi.setZero(3 * n_moving_, n_basis_);
465 Eigen::Vector3d d;
466 double r;
467 int first;
468 double b[4], db[4], d2b[4];
469 for (const auto& p: list_) {
470 if (!separation(p, x, d, r)) continue;
471 basis(r, first, b, db, d2b);
472 const Eigen::Vector3d n = d / r;
473 for (int k = 0; k < 4; ++k) {
474 const int index = first + k;
475 if (index < 0 || index >= n_basis_) continue;
476 phi(index) += b[k];
477 const Eigen::Vector3d g = db[k] * n;
478 dphi.block<3, 1>(3 * p.i, index) += g;
479 if (!p.frozen) dphi.block<3, 1>(3 * p.j, index) -= g;
480 }
481 }
482}
483
484void PairSplineModel::observe(const Eigen::VectorXd& x, double energy,
485 const Eigen::VectorXd& gradient, int slot)
486{
487 if (x.size() != 3 * n_moving_ || gradient.size() != x.size()) return;
488 if (!std::isfinite(energy) || !x.allFinite() || !gradient.allFinite())
489 return;
490 Eigen::VectorXd phi;
491 Eigen::MatrixXd dphi;
492 features(x, phi, dphi, slot);
493 const Eigen::Index m = n_basis_ + 1;
494 // Energy row: [1, phi].
495 Eigen::VectorXd row(m);
496 row(0) = 1.0;
497 row.tail(n_basis_) = phi;
498 ete_ += row * row.transpose();
499 ety_ += energy * row;
500 // Gradient rows: [0, dphi_i].
501 gtg_.selfadjointView<Eigen::Lower>().rankUpdate(dphi.transpose());
502 gty_ += dphi.transpose() * gradient;
503 sum_g2_ += gradient.squaredNorm();
504 n_gradient_rows_ += gradient.size();
505 ++n_obs_;
506}
507
509{
510 if (n_obs_ == 0) return false;
511 const Eigen::Index m = n_basis_ + 1;
512 const double we = 1.0 / (noise_energy_ * noise_energy_);
513 const double wg = 1.0 / (noise_gradient_ * noise_gradient_);
514 Eigen::MatrixXd A = we * ete_;
515 const Eigen::MatrixXd gtg = gtg_.selfadjointView<Eigen::Lower>();
516 A.block(1, 1, n_basis_, n_basis_) += wg * gtg;
517 Eigen::VectorXd rhs = we * ety_;
518 rhs.tail(n_basis_) += wg * gty_;
519 // Weight prior and a second-difference curvature prior along the knots.
520 const double pw = 1.0 / (prior_weight_ * prior_weight_);
521 const double pc = 1.0 / (prior_curvature_ * prior_curvature_);
522 for (Eigen::Index k = 1; k < m; ++k)
523 A(k, k) += pw;
524 for (Eigen::Index k = 1; k + 2 < m; ++k) {
525 Eigen::Vector3d d(1.0, -2.0, 1.0);
526 A.block<3, 3>(k, k) += pc * (d * d.transpose());
527 }
528 A(0, 0) += 1e-12;
529 Eigen::LDLT<Eigen::MatrixXd> ldlt(A);
530 if (ldlt.info() != Eigen::Success) return false;
531 weights_ = ldlt.solve(rhs);
532 if (!weights_.allFinite()) return false;
533 ready_ = true;
534 ++fit_count_;
535 tabulate();
536 const Eigen::VectorXd w = weights_.tail(n_basis_);
537 const double ss = sum_g2_ - 2.0 * w.dot(gty_) + w.dot(gtg * w);
538 gradient_residual_ =
539 n_gradient_rows_ > 0 && ss > 0.0
540 ? std::sqrt(ss / static_cast<double>(n_gradient_rows_))
541 : 0.0;
542 return true;
543}
544
545void PairSplineModel::loadCoordinates(const Eigen::VectorXd& x) const
546{
547 const std::size_t nm3 = static_cast<std::size_t>(3 * n_moving_);
548 const std::size_t nf3 = static_cast<std::size_t>(frozen_.size());
549 if (xall_.size() != nm3 + nf3) {
550 xall_.resize(nm3 + nf3);
551 std::copy(frozen_.data(), frozen_.data() + nf3, xall_.data() + nm3);
552 }
553 std::copy(x.data(), x.data() + nm3, xall_.data());
554}
555
556void PairSplineModel::sumRange(List& list, std::size_t begin, std::size_t end,
557 double& e, double* gp) const
558{
559 if (begin >= end || table_.empty()) return;
560 const double* X = xall_.data();
561 const int* oi = list.oi.data();
562 const int* oj = list.oj.data();
563 const double* sx = list.sx.data();
564 const double* sy = list.sy.data();
565 const double* sz = list.sz.data();
566 const double* coef = table_.front().data();
567 const int n_intervals = static_cast<int>(table_.size());
568 const int nm3 = static_cast<int>(3 * n_moving_);
569 const double rmin2 = r_min_ * r_min_, rcut2 = r_cut_ * r_cut_;
570 const double r_min = r_min_, inv_h = 1.0 / h_;
571 double esum = 0.0;
572 std::size_t k = begin;
573#if defined(__AVX2__)
574 const __m256d vr_min = _mm256_set1_pd(r_min);
575 const __m256d vinv_h = _mm256_set1_pd(inv_h);
576 for (; k + 4 <= end; k += 4) {
577 alignas(32) double dxs[4], dys[4], dzs[4];
578 int as[4], bs[4];
579 for (int lane = 0; lane < 4; ++lane) {
580 const std::size_t slot = k + static_cast<std::size_t>(lane);
581 as[lane] = oi[slot];
582 bs[lane] = oj[slot];
583 dxs[lane] = X[as[lane]] - X[bs[lane]] + sx[slot];
584 dys[lane] = X[as[lane] + 1] - X[bs[lane] + 1] + sy[slot];
585 dzs[lane] = X[as[lane] + 2] - X[bs[lane] + 2] + sz[slot];
586 }
587 const __m256d dx = _mm256_load_pd(dxs);
588 const __m256d dy = _mm256_load_pd(dys);
589 const __m256d dz = _mm256_load_pd(dzs);
590 const __m256d r2v = _mm256_add_pd(
591 _mm256_add_pd(_mm256_mul_pd(dx, dx), _mm256_mul_pd(dy, dy)),
592 _mm256_mul_pd(dz, dz));
593 const __m256d rv = _mm256_sqrt_pd(r2v);
594 const __m256d tv = _mm256_mul_pd(_mm256_sub_pd(rv, vr_min), vinv_h);
595 alignas(32) double r2s[4], rs[4], ts[4];
596 _mm256_store_pd(r2s, r2v);
597 _mm256_store_pd(rs, rv);
598 _mm256_store_pd(ts, tv);
599 for (int lane = 0; lane < 4; ++lane) {
600 if (r2s[lane] < rmin2 || r2s[lane] >= rcut2) continue;
601 const double t = ts[lane];
602 const int idx = static_cast<int>(t);
603 if (t < 0.0 || idx >= n_intervals) continue;
604 const double v = t - static_cast<double>(idx);
605 const double* c = coef + 4 * idx;
606 esum += c[0] + v * (c[1] + v * (c[2] + v * c[3]));
607 if (!gp) continue;
608 const double s =
609 (c[1] + v * (2.0 * c[2] + 3.0 * c[3] * v)) * inv_h / rs[lane];
610 const double gx = s * dxs[lane], gy = s * dys[lane],
611 gz = s * dzs[lane];
612 double* gi = gp + as[lane];
613 gi[0] += gx;
614 gi[1] += gy;
615 gi[2] += gz;
616 if (bs[lane] < nm3) {
617 double* gj = gp + bs[lane];
618 gj[0] -= gx;
619 gj[1] -= gy;
620 gj[2] -= gz;
621 }
622 }
623 }
624#endif
625 for (; k < end; ++k) {
626 const int a = oi[k];
627 const int b = oj[k];
628 const double dx = X[a] - X[b] + sx[k];
629 const double dy = X[a + 1] - X[b + 1] + sy[k];
630 const double dz = X[a + 2] - X[b + 2] + sz[k];
631 const double r2 = dx * dx + dy * dy + dz * dz;
632 if (r2 < rmin2 || r2 >= rcut2) continue;
633 const double r = std::sqrt(r2);
634 const double t = (r - r_min) * inv_h;
635 const int idx = static_cast<int>(t);
636 if (t < 0.0 || idx >= n_intervals) continue;
637 const double v = t - static_cast<double>(idx);
638 const double* c = coef + 4 * idx;
639 esum += c[0] + v * (c[1] + v * (c[2] + v * c[3]));
640 if (!gp) continue;
641 const double s = (c[1] + v * (2.0 * c[2] + 3.0 * c[3] * v)) * inv_h / r;
642 const double gx = s * dx, gy = s * dy, gz = s * dz;
643 double* gi = gp + a;
644 gi[0] += gx;
645 gi[1] += gy;
646 gi[2] += gz;
647 if (b < nm3) {
648 double* gj = gp + b;
649 gj[0] -= gx;
650 gj[1] -= gy;
651 gj[2] -= gz;
652 }
653 }
654 e += esum;
655}
656
657void PairSplineModel::sumIndexed(const List& list,
658 const std::vector<int>& index, double& e,
659 double* gp) const
660{
661 if (index.empty() || table_.empty()) return;
662 const double* X = xall_.data();
663 const int* oi = list.oi.data();
664 const int* oj = list.oj.data();
665 const double* sx = list.sx.data();
666 const double* sy = list.sy.data();
667 const double* sz = list.sz.data();
668 const double* coef = table_.front().data();
669 const int n_intervals = static_cast<int>(table_.size());
670 const int nm3 = static_cast<int>(3 * n_moving_);
671 const double rmin2 = r_min_ * r_min_, rcut2 = r_cut_ * r_cut_;
672 const double r_min = r_min_, inv_h = 1.0 / h_;
673 double esum = 0.0;
674 for (const int k: index) {
675 const int a = oi[static_cast<std::size_t>(k)];
676 const int b = oj[static_cast<std::size_t>(k)];
677 const double dx = X[a] - X[b] + sx[static_cast<std::size_t>(k)];
678 const double dy = X[a + 1] - X[b + 1] + sy[static_cast<std::size_t>(k)];
679 const double dz = X[a + 2] - X[b + 2] + sz[static_cast<std::size_t>(k)];
680 const double r2 = dx * dx + dy * dy + dz * dz;
681 if (r2 < rmin2 || r2 >= rcut2) continue;
682 const double r = std::sqrt(r2);
683 const double t = (r - r_min) * inv_h;
684 const int idx = static_cast<int>(t);
685 if (t < 0.0 || idx >= n_intervals) continue;
686 const double v = t - static_cast<double>(idx);
687 const double* c = coef + 4 * idx;
688 esum += c[0] + v * (c[1] + v * (c[2] + v * c[3]));
689 if (!gp) continue;
690 const double s = (c[1] + v * (2.0 * c[2] + 3.0 * c[3] * v)) * inv_h / r;
691 const double gx = s * dx, gy = s * dy, gz = s * dz;
692 double* gi = gp + a;
693 gi[0] += gx;
694 gi[1] += gy;
695 gi[2] += gz;
696 if (b < nm3) {
697 double* gj = gp + b;
698 gj[0] -= gx;
699 gj[1] -= gy;
700 gj[2] -= gz;
701 }
702 }
703 e += esum;
704}
705
706double PairSplineModel::maskedEnergy(const Eigen::VectorXd& x,
707 const std::vector<char>& atom_mask,
708 Eigen::VectorXd* gradient, int slot) const
709{
710 if (gradient) gradient->setZero(x.size());
711 if (!ready_ || x.size() != 3 * n_moving_ ||
712 atom_mask.size() != static_cast<std::size_t>(n_moving_))
713 return 0.0;
714 List& list = ensureList(x, slot);
715 loadCoordinates(x);
716 if (list.masked_atoms != atom_mask) {
717 const int nm3 = static_cast<int>(3 * n_moving_);
718 list.masked.clear();
719 for (int k = 0; k < static_cast<int>(list.oi.size()); ++k) {
720 const int a = list.oi[static_cast<std::size_t>(k)] / 3;
721 const int b = list.oj[static_cast<std::size_t>(k)];
722 if (atom_mask[static_cast<std::size_t>(a)] ||
723 (b < nm3 && atom_mask[static_cast<std::size_t>(b / 3)]))
724 list.masked.push_back(k);
725 }
726 list.masked_atoms = atom_mask;
727 }
728 double e = 0.0;
729 sumIndexed(list, list.masked, e, gradient ? gradient->data() : nullptr);
730 return e;
731}
732
733double PairSplineModel::energy(const Eigen::VectorXd& x,
734 Eigen::VectorXd* gradient, int slot) const
735{
736 if (gradient) gradient->setZero(x.size());
737 if (!ready_ || x.size() != 3 * n_moving_) return 0.0;
738 List& list = ensureList(x, slot);
739 loadCoordinates(x);
740 const std::size_t n_pairs = list.oi.size();
741 double* gp = gradient ? gradient->data() : nullptr;
742 if (list.n_near >= n_pairs) {
743 double e = weights_(0);
744 sumRange(list, 0, n_pairs, e, gp);
745 return e;
746 }
747 // Tail pairs change slowly: their sum is held as a linear model of the
748 // geometry it was taken at, so the surrogate stays one fixed function
749 // between refreshes.
750 bool stale = list.tail_fit != fit_count_ ||
751 list.tail_positions.size() != x.size() ||
752 list.tail_gradient.size() != x.size();
753 if (!stale && tail_refresh_ > 0.0) {
754 for (Eigen::Index i = 0; i < n_moving_ && !stale; ++i)
755 stale =
756 (x.segment<3>(3 * i) - list.tail_positions.segment<3>(3 * i))
757 .squaredNorm() > tail_refresh_ * tail_refresh_;
758 }
759 if (stale) {
760 list.tail_energy = 0.0;
761 list.tail_gradient.setZero(x.size());
762 sumRange(list, list.n_near, n_pairs, list.tail_energy,
763 list.tail_gradient.data());
764 list.tail_positions = x;
765 list.tail_fit = fit_count_;
766 }
767 double e = weights_(0) + list.tail_energy +
768 list.tail_gradient.dot(x - list.tail_positions);
769 if (gradient) *gradient = list.tail_gradient;
770 sumRange(list, 0, list.n_near, e, gp);
771 return e;
772}
773
774double PairSplineModel::partialEnergy(const Eigen::VectorXd& x,
775 const std::vector<char>& atom_mask,
776 Eigen::VectorXd* gradient, int slot) const
777{
778 if (gradient && gradient->size() != x.size()) gradient->setZero(x.size());
779 if (!ready_ || x.size() != 3 * n_moving_ ||
780 atom_mask.size() != static_cast<std::size_t>(n_moving_))
781 return 0.0;
782 const auto& list_ = ensureList(x, slot).pairs;
783 double e = 0.0;
784 Eigen::Vector3d d;
785 double r;
786 int first;
787 double b[4], db[4], d2b[4];
788 for (const auto& p: list_) {
789 const bool mi = atom_mask[static_cast<std::size_t>(p.i)] != 0;
790 const bool mj =
791 !p.frozen && atom_mask[static_cast<std::size_t>(p.j)] != 0;
792 if (!mi && !mj) continue;
793 if (!separation(p, x, d, r)) continue;
794 basis(r, first, b, db, d2b);
795 double phi = 0.0, dphi = 0.0;
796 for (int k = 0; k < 4; ++k) {
797 const int index = first + k;
798 if (index < 0 || index >= n_basis_) continue;
799 phi += weights_(1 + index) * b[k];
800 dphi += weights_(1 + index) * db[k];
801 }
802 e += phi;
803 if (gradient) {
804 const Eigen::Vector3d g = (dphi / r) * d;
805 if (mi) gradient->segment<3>(3 * p.i) += g;
806 if (mj) gradient->segment<3>(3 * p.j) -= g;
807 }
808 }
809 return e;
810}
811
812Eigen::MatrixXd PairSplineModel::hessian(const Eigen::VectorXd& x,
813 const std::vector<Eigen::Index>& dofs,
814 int slot) const
815{
816 const Eigen::Index n = static_cast<Eigen::Index>(dofs.size());
817 Eigen::MatrixXd H = Eigen::MatrixXd::Zero(n, n);
818 if (!ready_ || x.size() != 3 * n_moving_) return H;
819 const auto& list_ = ensureList(x, slot).pairs;
820 // Atom -> first row of its block in H, or -1 when absent. Only whole
821 // atoms are supported; a partial atom contributes its present rows.
822 std::vector<Eigen::Index> row_of(static_cast<std::size_t>(x.size()), -1);
823 for (Eigen::Index k = 0; k < n; ++k)
824 row_of[static_cast<std::size_t>(dofs[k])] = k;
825 Eigen::Vector3d d;
826 double r;
827 for (const auto& p: list_) {
828 if (!separation(p, x, d, r)) continue;
829 double phi, dphi, d2phi;
830 radial(r, phi, dphi, d2phi);
831 const Eigen::Vector3d nvec = d / r;
832 const Eigen::Matrix3d block =
833 d2phi * (nvec * nvec.transpose()) +
834 (dphi / r) *
835 (Eigen::Matrix3d::Identity() - nvec * nvec.transpose());
836 const auto add = [&](int ai, int aj, double sign) {
837 for (int a = 0; a < 3; ++a) {
838 const Eigen::Index ra =
839 row_of[static_cast<std::size_t>(3 * ai + a)];
840 if (ra < 0) continue;
841 for (int c = 0; c < 3; ++c) {
842 const Eigen::Index rc =
843 row_of[static_cast<std::size_t>(3 * aj + c)];
844 if (rc < 0) continue;
845 H(ra, rc) += sign * block(a, c);
846 }
847 }
848 };
849 add(p.i, p.i, 1.0);
850 if (!p.frozen) {
851 add(p.j, p.j, 1.0);
852 add(p.i, p.j, -1.0);
853 add(p.j, p.i, -1.0);
854 }
855 }
856 return H;
857}
858
859} // namespace neb
860} // namespace gpr
@ x
Definition Enums.h:28
void displacement(const double p[3], const double q[3], double dr[3]) const
Displacement from p to q. Cartesian q - p when the cell is zero.
Definition MinImage.h:210
PairSplineModel(Eigen::Index n_moving, Eigen::VectorXd frozen_positions, const std::array< double, 9 > &cell, double r_min, double r_cut, double spacing)
void setPrior(double weight_sigma, double curvature_sigma)
void setNoise(double energy_sigma, double gradient_sigma)
Noise standard deviations of the energy and gradient rows.
double energy(const Eigen::VectorXd &x, Eigen::VectorXd *gradient, int slot=0) const
bool fit()
Solve for the weights. Returns false without enough rows.
void observe(const Eigen::VectorXd &x, double energy, const Eigen::VectorXd &gradient, int slot=0)
Accumulate one measurement into the normal equations.
void radial(double r, double &phi, double &dphi, double &d2phi) const
Radial function and its first two derivatives at r.
void setTailSplit(double split, double refresh)
double minimumSeparation(const Eigen::VectorXd &x) const
Smallest moving-moving or moving-frozen separation at x.
Eigen::MatrixXd hessian(const Eigen::VectorXd &x, const std::vector< Eigen::Index > &dofs, int slot=0) const
Hessian block over the listed coordinates at x.
void staleTail(int slot)
Marks the slot's tail sum for recomputation at the next evaluation.
double maskedEnergy(const Eigen::VectorXd &x, const std::vector< char > &atom_mask, Eigen::VectorXd *gradient, int slot=0) const
double partialEnergy(const Eigen::VectorXd &x, const std::vector< char > &atom_mask, Eigen::VectorXd *gradient, int slot=0) const
eon_relax_band_t eon_relax_surface_fn void eon_relax_outcome_t * out
int status
The nudged elastic band: path, GP-NEB driver, configuration and result, acquisition,...
Gaussian-process regression, kernels, priors, and the searches that run on the surrogate.
Definition Macros.h:16
STL namespace.