Loading...
Searching...
No Matches
SexpatOperator.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 <algorithm>
6#include <cmath>
7#include <memory>
8#include <span>
9#include <stdexcept>
10#include <utility>
11#include <vector>
12
16#include "KernelOperator.h"
17#include "SexpatCF.h"
19#ifdef GPR_LINALG_SCALAPACK
20#include "../linalg/Backend.h"
21#endif
22
23namespace gpr {
24
25namespace {
26#ifdef GPR_PLAIN_PREDICT_SUM
27struct CompSum {
28 double sum = 0.0;
29 double corr = 0.0;
30 inline void add(double x)
31 {
32 sum += x;
33 }
34 inline double value() const
35 {
36 return sum + corr;
37 }
38};
39#else
40using CompSum = gpr::linalg::CompensatedSum;
41#endif
42} // namespace
43
44namespace {
45Eigen::MatrixXd assembleRadialPairCovariance(
46 std::span<const CutoffPairFeatures> left_rows,
47 std::span<const CutoffPairFeatures> right_rows, Eigen::Index dof,
48 const Eigen::VectorXd& lengths, double magnitude)
49{
50 const Eigen::Index nl = static_cast<Eigen::Index>(left_rows.size());
51 const Eigen::Index nr = static_cast<Eigen::Index>(right_rows.size());
52 Eigen::MatrixXd result(nl * (dof + 1), nr * (dof + 1));
53 using Vector = Eigen::Matrix<long double, Eigen::Dynamic, 1>;
54 using Matrix = Eigen::Matrix<long double, Eigen::Dynamic, Eigen::Dynamic>;
55 using Matrix3 = Eigen::Matrix<long double, 3, 3>;
56 const auto add_gradient = [&](Vector& output, const CutoffPairFeature& pair,
57 long double weight) {
58 const auto contribution =
59 (weight * pair.gradient.cast<long double>()).eval();
60 output.segment<3>(3 * pair.first) += contribution;
61 if (3 * pair.second < dof)
62 output.segment<3>(3 * pair.second) -= contribution;
63 };
64
65 for (Eigen::Index i = 0; i < nl; ++i) {
66 for (Eigen::Index j = 0; j < nr; ++j) {
67 long double squared_distance = 0.0L;
68 Vector left_projection = Vector::Zero(dof);
69 Vector right_projection = Vector::Zero(dof);
70 Matrix jacobian_cross = Matrix::Zero(dof, dof);
72 left_rows[i], right_rows[j],
73 [&](const CutoffPairFeature* a, const CutoffPairFeature* b) {
74 const Eigen::Index type = a ? a->type : b->type;
75 const long double length =
76 lengths.data()[lengths.size() == 1 ? 0 : type];
77 const long double inverse = 1.0L / (length * length);
78 const long double delta =
79 (a ? a->value : 0.0L) - (b ? b->value : 0.0L);
80 squared_distance += inverse * delta * delta;
81 if (a) add_gradient(left_projection, *a, inverse * delta);
82 if (b) add_gradient(right_projection, *b, inverse * delta);
83 if (!a || !b) return;
84 // A pair Jacobian has at most two Cartesian atom blocks.
85 const Matrix3 cross =
86 inverse * a->gradient.cast<long double>() *
87 b->gradient.cast<long double>().transpose();
88 jacobian_cross.block<3, 3>(3 * a->first, 3 * b->first) +=
89 cross;
90 if (3 * b->second < dof)
91 jacobian_cross.block<3, 3>(3 * a->first,
92 3 * b->second) -= cross;
93 if (3 * a->second < dof) {
94 jacobian_cross.block<3, 3>(3 * a->second,
95 3 * b->first) -= cross;
96 if (3 * b->second < dof)
97 jacobian_cross.block<3, 3>(3 * a->second,
98 3 * b->second) += cross;
99 }
100 });
101 const long double kernel = magnitude * std::exp(-squared_distance);
102 result(i, j) = static_cast<double>(kernel);
103 for (Eigen::Index a = 0; a < dof; ++a) {
104 result((a + 1) * nl + i, j) =
105 static_cast<double>(-2.0L * kernel * left_projection(a));
106 result(i, (a + 1) * nr + j) =
107 static_cast<double>(2.0L * kernel * right_projection(a));
108 for (Eigen::Index b = 0; b < dof; ++b)
109 result((a + 1) * nl + i, (b + 1) * nr + j) =
110 static_cast<double>(
111 kernel *
112 (2.0L * jacobian_cross(a, b) -
113 4.0L * left_projection(a) * right_projection(b)));
114 }
115 }
116 }
117 return result;
118}
119} // namespace
120
122 const Eigen::MatrixXd& left_positions,
123 const Eigen::MatrixXd& right_positions) const
124{
125 const Eigen::Index dof = 3 * primitive_->conf_info.atoms_mov.type.size();
126 if (dof <= 0 || left_positions.cols() != dof ||
127 right_positions.cols() != dof || !left_positions.allFinite() ||
128 !right_positions.allFinite())
129 throw std::invalid_argument(
130 "Sexpat joint covariance requires molecular Cartesian rows");
131 const auto& lengths = primitive_->lengthScale;
132 bool positive_lengths =
133 lengths.size() == 1 || lengths.size() == primitive_->conf_info.n_pt;
134 for (Eigen::Index i = 0; i < lengths.size(); ++i)
135 positive_lengths = positive_lengths && lengths.data()[i] > 0.0;
136 // Infinite lengths remove inactive pair types with an exact zero weight.
137 if (!positive_lengths)
138 throw std::invalid_argument(
139 "Sexpat joint covariance requires positive pair length scales");
140
141 const auto left_rows = radialPairFeatures(
142 left_positions, primitive_->conf_info, primitive_->farFieldRadius());
143 const auto right_rows = radialPairFeatures(
144 right_positions, primitive_->conf_info, primitive_->farFieldRadius());
145 return assembleRadialPairCovariance(
146 left_rows, right_rows, dof,
147 Eigen::Map<const Eigen::VectorXd>(lengths.data(), lengths.size()),
148 primitive_->magnSigma2);
149}
150
152 const Eigen::MatrixXd& positions) const
153{
154 const Eigen::Index dof = 3 * primitive_->conf_info.atoms_mov.type.size();
155 if (dof <= 0 || positions.cols() != dof || !positions.allFinite())
156 throw std::invalid_argument(
157 "Sexpat joint covariance requires molecular Cartesian rows");
158 const auto& parameters = primitive_->lengthScale;
159 const Eigen::VectorXd lengths =
160 Eigen::Map<const Eigen::VectorXd>(parameters.data(), parameters.size());
161 if ((lengths.size() != 1 && lengths.size() != primitive_->conf_info.n_pt) ||
162 !(lengths.array() > 0.0).all())
163 throw std::invalid_argument(
164 "Sexpat joint covariance requires positive pair length scales");
165 return [rows = radialPairFeatures(positions, primitive_->conf_info,
166 primitive_->farFieldRadius()),
167 lengths, magnitude = primitive_->magnSigma2,
168 dof](Eigen::Index i, Eigen::Index j) -> Eigen::MatrixXd {
169 const auto count = static_cast<Eigen::Index>(rows.size());
170 if (i < 0 || j < 0 || i >= count || j >= count)
171 throw std::out_of_range("pair covariance tile index is invalid");
172 const std::span<const CutoffPairFeatures> span(rows);
173 return assembleRadialPairCovariance(
174 span.subspan(i, 1), span.subspan(j, 1), dof, lengths, magnitude);
175 };
176}
177
178bool Sexpat::meanHessianVector(const Coord& training,
179 const Eigen::VectorXd& weights,
180 const Eigen::VectorXd& position,
181 const Eigen::VectorXd& direction,
182 Eigen::VectorXd& action) const
183{
184 const auto fitted = prepareMeanHessianVector(training, weights);
185 return fitted && fitted(position, direction, action);
186}
187
189 const Eigen::MatrixXd& training, const Eigen::VectorXd& weights) const
190{
191 const auto prepare = prepareMeanHessian(training, weights);
192 if (!prepare) return {};
193 return
194 [prepare](const Eigen::VectorXd& position,
195 const Eigen::VectorXd& direction, Eigen::VectorXd& action) {
196 const auto apply = prepare(position);
197 return apply && apply(direction, action);
198 };
199}
200
201namespace {
202
203using LongVector = Eigen::Matrix<long double, Eigen::Dynamic, 1>;
204using LongMatrix = Eigen::Matrix<long double, Eigen::Dynamic, Eigen::Dynamic>;
205using LongVector3 = Eigen::Matrix<long double, 3, 1>;
206using LongMatrix3 = Eigen::Matrix<long double, 3, 3>;
207
208constexpr Eigen::Index kHessianBlock = 8;
209using HessianPacket = Eigen::Array<double, kHessianBlock, 1>;
210
211// Branchless Knuth TwoSum / Ogita-Rump-Oishi Sum2 compensation over SIMD lanes.
212struct PacketTwoSum {
213 HessianPacket sum = HessianPacket::Zero();
214 HessianPacket err = HessianPacket::Zero();
215
216 inline void add(const HessianPacket& value) noexcept
217 {
218 const HessianPacket s = sum + value;
219 const HessianPacket v = s - sum;
220 err += (sum - (s - v)) + (value - v);
221 sum = s;
222 }
223
224 [[nodiscard]] inline HessianPacket value() const noexcept
225 {
226 return sum + err;
227 }
228};
229
230struct CutoffTrainPair {
231 Eigen::Index first = 0;
232 Eigen::Index second = 0;
233 Eigen::Index type = 0;
234 double value = 0.0;
235 double contraction = 0.0;
236};
237
238template <typename LeftRow, typename Function>
239void forEachPairUnion(const LeftRow& left, const CutoffPairFeatures& right,
240 Function&& function)
241{
242 std::size_t i = 0, j = 0;
243 while (i < left.size() || j < right.size()) {
244 if (j == right.size() ||
245 (i < left.size() &&
246 std::make_pair(left[i].first, left[i].second) <
247 std::make_pair(right[j].first, right[j].second))) {
248 function(&left[i++], nullptr);
249 } else if (i == left.size() ||
250 std::make_pair(right[j].first, right[j].second) <
251 std::make_pair(left[i].first, left[i].second)) {
252 function(nullptr, &right[j++]);
253 } else {
254 function(&left[i++], &right[j++]);
255 }
256 }
257}
258
259[[nodiscard]] bool validSexpatHessianInputs(const SexpatCF& source,
260 const Eigen::MatrixXd& training,
261 const Eigen::VectorXd& weights)
262{
263 const Eigen::Index n = training.rows(), dof = training.cols();
264 const auto& conf = source.getConfInfo();
265 const auto& lengths = source.getAtomisticLengthScaleRef();
266 return n >= 0 && dof > 0 && dof == 3 * conf.atoms_mov.type.size() &&
267 weights.size() == n * (dof + 1) && training.allFinite() &&
268 weights.allFinite() && lengths.size() > 0 &&
269 (lengths.size() == 1 || lengths.size() == conf.n_pt) &&
270 (lengths.array() > 0.0).all() && lengths.allFinite() &&
271 std::isfinite(source.getMagnSigma2()) &&
272 source.getMagnSigma2() >= 0.0 &&
273 std::isfinite(source.farFieldRadius()) &&
274 source.farFieldRadius() >= 0.0 &&
275 !(source.farFieldRadius() > 0.0 && conf.pair_cutoff > 0.0);
276}
277
278// k = sigma^2 exp(-d) vanishes identically at sigma^2 = 0, so its Hessian is
279// exactly zero for every length scale and coefficient.
280Sexpat::MeanHessianMatrixFunction zeroSexpatMeanHessianMatrix(Eigen::Index dof)
281{
282 return [dof](const Eigen::VectorXd& position, Eigen::MatrixXd& hessian) {
283 if (position.size() != dof || !position.allFinite()) return false;
284 hessian = Eigen::MatrixXd::Zero(dof, dof);
285 return true;
286 };
287}
288
289KernelOperator::MeanHessianPreparation zeroSexpatMeanHessian(Eigen::Index dof)
290{
291 return
292 [dof](
293 const Eigen::VectorXd& position) -> KernelOperator::HessianAction {
294 if (position.size() != dof || !position.allFinite()) return {};
295 return [dof](const Eigen::VectorXd& direction,
296 Eigen::VectorXd& action) {
297 if (direction.size() != dof || !direction.allFinite())
298 return false;
299 action = Eigen::VectorXd::Zero(dof);
300 return true;
301 };
302 };
303}
304
305struct SexpatMeanBasisDouble {
306 std::shared_ptr<const SexpatCF> primitive;
307 Eigen::VectorXd energy_weights;
308 std::vector<double> inverse_lengths;
309 Eigen::Index n = 0;
310 Eigen::Index dof = 0;
311 bool fixed_vocabulary = false;
312 Eigen::Index num_pairs = 0;
313 std::vector<Eigen::Index> pair_first;
314 std::vector<Eigen::Index> pair_second;
315 std::vector<Eigen::Index> pair_type;
316 std::vector<double> packed_values;
317 std::vector<double> packed_contractions;
318 std::vector<std::vector<CutoffTrainPair>> cutoff_rows;
319};
320
321struct SexpatMeanHessianDouble {
322 CutoffPairFeatures pairs;
323 std::vector<Eigen::Matrix3d> local;
324 Eigen::MatrixXd u, v;
325 Eigen::VectorXd kernel, weighted_scalar;
326 bool translation_invariant = true;
327};
328
329struct SexpatMeanBasisLong {
330 std::shared_ptr<const SexpatCF> primitive;
331 std::vector<CutoffPairFeatures> rows;
332 std::vector<std::vector<long double>> gradient_weights;
333 Eigen::VectorXd energy_weights;
334 Eigen::Index n = 0;
335 Eigen::Index dof = 0;
336};
337
338// H = sum_i k_i(s_i u_i u_i^T + v_i u_i^T + u_i v_i^T) + sparse radial
339// blocks. The query forms the exponentials and pair contractions once.
340struct SexpatMeanHessianLong {
341 CutoffPairFeatures pairs;
342 std::vector<LongMatrix3> local;
343 LongMatrix u, v;
344 LongVector kernel, weighted_scalar;
345 bool translation_invariant = true;
346};
347
348std::shared_ptr<const SexpatMeanBasisDouble> prepareSexpatMeanBasisDouble(
349 const SexpatCF& source, const Eigen::MatrixXd& training,
350 const Eigen::VectorXd& weights)
351{
352 if (!validSexpatHessianInputs(source, training, weights)) return nullptr;
353 const Eigen::Index n = training.rows(), dof = training.cols();
354 auto primitive = std::make_shared<SexpatCF>(source);
355 primitive->clearDistanceCache();
356 auto basis = std::make_shared<SexpatMeanBasisDouble>();
357 basis->n = n;
358 basis->dof = dof;
359 basis->energy_weights = weights.head(n);
360 const auto& conf = primitive->getConfInfo();
361 const auto& lengths = primitive->getAtomisticLengthScaleRef();
362 // Every pair term carries 2 / l^2, so l^2 and 2 / l^2 must both be normal
363 // binary64; the long double path has the wider exponent range.
364 basis->inverse_lengths.resize(static_cast<std::size_t>(lengths.size()));
365 for (Eigen::Index t = 0; t < lengths.size(); ++t) {
366 const double square = lengths.data()[t] * lengths.data()[t];
367 const double inverse = 1.0 / square;
368 if (!std::isnormal(square) || !std::isnormal(2.0 * inverse))
369 throw std::range_error(
370 "Sexpat double Hessian: inverse squared length scale is not "
371 "representable in binary64; use HessianPrecision::LongDouble");
372 basis->inverse_lengths[static_cast<std::size_t>(t)] = inverse;
373 }
374 const auto representable = [](double contraction) {
375 if (!std::isfinite(contraction))
376 throw std::range_error(
377 "Sexpat double Hessian: gradient-weight contraction is not "
378 "representable in binary64; use HessianPrecision::LongDouble");
379 return contraction;
380 };
381 const auto rows =
382 radialPairFeatures(training, conf, primitive->farFieldRadius());
383 for (Eigen::Index i = 0; i < n; ++i) {
384 for (const auto& pair: rows[i]) {
385 if (pair.type < 0 ||
386 (lengths.size() != 1 && pair.type >= lengths.size()))
387 return nullptr;
388 }
389 }
390 if (conf.pair_cutoff == 0.0 && n > 0) {
391 const Eigen::Index P = static_cast<Eigen::Index>(rows[0].size());
392 for (Eigen::Index i = 1; i < n; ++i) {
393 if (static_cast<Eigen::Index>(rows[i].size()) != P) return nullptr;
394 for (Eigen::Index p = 0; p < P; ++p) {
395 if (rows[i][p].first != rows[0][p].first ||
396 rows[i][p].second != rows[0][p].second ||
397 rows[i][p].type != rows[0][p].type)
398 return nullptr;
399 }
400 }
401 basis->fixed_vocabulary = true;
402 basis->num_pairs = P;
403 basis->pair_first.resize(P);
404 basis->pair_second.resize(P);
405 basis->pair_type.resize(P);
406 for (Eigen::Index p = 0; p < P; ++p) {
407 basis->pair_first[p] = rows[0][p].first;
408 basis->pair_second[p] = rows[0][p].second;
409 basis->pair_type[p] = rows[0][p].type;
410 }
411 const Eigen::Index n_blocks = (n + kHessianBlock - 1) / kHessianBlock;
412 basis->packed_values.assign(
413 static_cast<std::size_t>(n_blocks * P * kHessianBlock), 0.0);
414 basis->packed_contractions.assign(
415 static_cast<std::size_t>(n_blocks * P * kHessianBlock), 0.0);
416 for (Eigen::Index b_idx = 0; b_idx < n_blocks; ++b_idx) {
417 const Eigen::Index i0 = b_idx * kHessianBlock;
418 const Eigen::Index count = std::min(kHessianBlock, n - i0);
419 for (Eigen::Index p = 0; p < P; ++p) {
420 const std::size_t offset =
421 static_cast<std::size_t>((b_idx * P + p) * kHessianBlock);
422 for (Eigen::Index k = 0; k < count; ++k) {
423 const Eigen::Index i = i0 + k;
424 const auto& pair = rows[i][p];
425 linalg::CompensatedSum contraction;
426 for (Eigen::Index d = 0; d < 3; ++d) {
427 const double first =
428 weights((3 * pair.first + d + 1) * n + i);
429 const double second =
430 pair.second < dof / 3
431 ? weights((3 * pair.second + d + 1) * n + i)
432 : 0.0;
433 contraction.add((first - second) * pair.gradient(d));
434 }
435 basis->packed_values[offset + k] = pair.value;
436 basis->packed_contractions[offset + k] =
437 representable(contraction.value());
438 }
439 }
440 }
441 } else {
442 basis->fixed_vocabulary = false;
443 basis->cutoff_rows.resize(n);
444 for (Eigen::Index i = 0; i < n; ++i) {
445 auto& dst = basis->cutoff_rows[i];
446 dst.reserve(rows[i].size());
447 for (const auto& pair: rows[i]) {
448 linalg::CompensatedSum contraction;
449 for (Eigen::Index d = 0; d < 3; ++d) {
450 const double first =
451 weights((3 * pair.first + d + 1) * n + i);
452 const double second =
453 pair.second < dof / 3
454 ? weights((3 * pair.second + d + 1) * n + i)
455 : 0.0;
456 contraction.add((first - second) * pair.gradient(d));
457 }
458 dst.push_back({pair.first, pair.second, pair.type, pair.value,
459 representable(contraction.value())});
460 }
461 }
462 }
463 basis->primitive = std::move(primitive);
464 return basis;
465}
466
467std::shared_ptr<const SexpatMeanHessianDouble> prepareSexpatMeanHessianDouble(
468 const SexpatMeanBasisDouble& basis, const Eigen::VectorXd& position)
469{
470 const Eigen::Index n = basis.n, dof = basis.dof;
471 if (position.size() != dof || !position.allFinite()) return nullptr;
472 const SexpatCF& primitive = *basis.primitive;
473 const Coord query_position = position.transpose();
474 auto hessian = std::make_shared<SexpatMeanHessianDouble>();
475 hessian->pairs = radialPairFeatures(query_position, primitive.getConfInfo(),
476 primitive.farFieldRadius())
477 .front();
478 const auto& query = hessian->pairs;
479 const auto& lengths = primitive.getAtomisticLengthScaleRef();
480 for (const auto& pair: query) {
481 if (pair.type < 0 ||
482 (lengths.size() != 1 && pair.type >= lengths.size()))
483 return nullptr;
484 }
485 const auto inverse_length = [&](Eigen::Index type) -> double {
486 return basis.inverse_lengths[static_cast<std::size_t>(
487 lengths.size() == 1 ? 0 : type)];
488 };
489
490 if (basis.fixed_vocabulary) {
491 const Eigen::Index P = basis.num_pairs;
492 if (static_cast<Eigen::Index>(query.size()) != P) return nullptr;
493 std::vector<double> inv_p(P), q_val(P);
494 std::vector<Eigen::Vector3d> two_inv_grad(P);
495 std::vector<Eigen::Index> first3(P), second3(P);
496 for (Eigen::Index p = 0; p < P; ++p) {
497 if (query[p].first != basis.pair_first[p] ||
498 query[p].second != basis.pair_second[p] ||
499 query[p].type != basis.pair_type[p])
500 return nullptr;
501 inv_p[p] = inverse_length(query[p].type);
502 q_val[p] = query[p].value;
503 two_inv_grad[p] = (2.0 * inv_p[p]) * query[p].gradient;
504 first3[p] = 3 * query[p].first;
505 second3[p] = query[p].second < dof / 3 ? 3 * query[p].second : -1;
506 }
507
508 hessian->u.resize(n, dof);
509 hessian->v.resize(n, dof);
510 hessian->kernel.resize(n);
511 hessian->weighted_scalar.resize(n);
512 std::vector<PacketTwoSum> grad_coeff_pkt(P);
513 PacketTwoSum scalar_sum_pkt;
514 Eigen::Matrix<double, kHessianBlock, Eigen::Dynamic, Eigen::ColMajor>
515 u_blk(kHessianBlock, dof);
516 Eigen::Matrix<double, kHessianBlock, Eigen::Dynamic, Eigen::ColMajor>
517 v_blk(kHessianBlock, dof);
518
519 const Eigen::Index n_blocks = (n + kHessianBlock - 1) / kHessianBlock;
520 for (Eigen::Index b_idx = 0; b_idx < n_blocks; ++b_idx) {
521 const Eigen::Index i0 = b_idx * kHessianBlock;
522 const Eigen::Index count = std::min(kHessianBlock, n - i0);
523 u_blk.setZero();
524 v_blk.setZero();
525
526 PacketTwoSum dist_comp, scalar_comp;
527 for (Eigen::Index k = 0; k < count; ++k)
528 scalar_comp.sum(k) = basis.energy_weights(i0 + k);
529
530 const double* __restrict__ val_base =
531 basis.packed_values.data() +
532 static_cast<std::size_t>(b_idx * P * kHessianBlock);
533 const double* __restrict__ c_base =
534 basis.packed_contractions.data() +
535 static_cast<std::size_t>(b_idx * P * kHessianBlock);
536
537 for (Eigen::Index p = 0; p < P; ++p) {
538 const double inv = inv_p[p];
539 const HessianPacket t_val = Eigen::Map<const HessianPacket>(
540 val_base + p * kHessianBlock);
541 const HessianPacket c =
542 Eigen::Map<const HessianPacket>(c_base + p * kHessianBlock);
543 const HessianPacket delta = t_val - q_val[p];
544 dist_comp.add((inv * delta) * delta);
545 scalar_comp.add((-2.0 * inv) * (delta * c));
546
547 const Eigen::Vector3d& g = two_inv_grad[p];
548 const Eigen::Index a = first3[p];
549 const Eigen::Index b = second3[p];
550 double* __restrict__ ua = u_blk.col(a).data();
551 double* __restrict__ va = v_blk.col(a).data();
552 if (b >= 0) {
553 double* __restrict__ ub = u_blk.col(b).data();
554 double* __restrict__ vb = v_blk.col(b).data();
555 for (int d = 0; d < 3; ++d) {
556 const HessianPacket u_term = delta * g(d);
557 const HessianPacket v_term = c * g(d);
558 Eigen::Map<HessianPacket>(ua + d * kHessianBlock) +=
559 u_term;
560 Eigen::Map<HessianPacket>(ub + d * kHessianBlock) -=
561 u_term;
562 Eigen::Map<HessianPacket>(va + d * kHessianBlock) +=
563 v_term;
564 Eigen::Map<HessianPacket>(vb + d * kHessianBlock) -=
565 v_term;
566 }
567 } else {
568 for (int d = 0; d < 3; ++d) {
569 const HessianPacket u_term = delta * g(d);
570 const HessianPacket v_term = c * g(d);
571 Eigen::Map<HessianPacket>(ua + d * kHessianBlock) +=
572 u_term;
573 Eigen::Map<HessianPacket>(va + d * kHessianBlock) +=
574 v_term;
575 }
576 }
577 }
578
579 const HessianPacket dist = dist_comp.value();
580 const HessianPacket scalar = scalar_comp.value();
581 HessianPacket kern = HessianPacket::Zero();
582 HessianPacket w_scalar = HessianPacket::Zero();
583 for (Eigen::Index k = 0; k < count; ++k) {
584 kern(k) = primitive.getMagnSigma2() * numerics::exp(-dist(k));
585 w_scalar(k) = kern(k) * scalar(k);
586 }
587 scalar_sum_pkt.add(w_scalar);
588
589 for (Eigen::Index p = 0; p < P; ++p) {
590 const HessianPacket t_val = Eigen::Map<const HessianPacket>(
591 val_base + p * kHessianBlock);
592 const HessianPacket c =
593 Eigen::Map<const HessianPacket>(c_base + p * kHessianBlock);
594 const HessianPacket delta = t_val - q_val[p];
595 const HessianPacket term =
596 (2.0 * inv_p[p]) * (w_scalar * delta + kern * c);
597 grad_coeff_pkt[p].add(term);
598 }
599
600 if (count == kHessianBlock) {
601 hessian->kernel.segment<kHessianBlock>(i0) = kern.matrix();
602 hessian->weighted_scalar.segment<kHessianBlock>(i0) =
603 w_scalar.matrix();
604 for (Eigen::Index d = 0; d < dof; ++d) {
605 hessian->u.col(d).segment<kHessianBlock>(i0) = u_blk.col(d);
606 hessian->v.col(d).segment<kHessianBlock>(i0) = v_blk.col(d);
607 }
608 } else {
609 hessian->kernel.segment(i0, count) = kern.head(count).matrix();
610 hessian->weighted_scalar.segment(i0, count) =
611 w_scalar.head(count).matrix();
612 for (Eigen::Index d = 0; d < dof; ++d) {
613 hessian->u.col(d).segment(i0, count) =
614 u_blk.col(d).head(count);
615 hessian->v.col(d).segment(i0, count) =
616 v_blk.col(d).head(count);
617 }
618 }
619 }
620
621 linalg::CompensatedSum scalar_sum_red;
622 for (Eigen::Index k = 0; k < kHessianBlock; ++k) {
623 scalar_sum_red.add(scalar_sum_pkt.sum(k));
624 scalar_sum_red.add(scalar_sum_pkt.err(k));
625 }
626 const double scalar_sum = scalar_sum_red.value();
627
628 hessian->local.reserve(P);
629 for (Eigen::Index p = 0; p < P; ++p) {
631 for (Eigen::Index k = 0; k < kHessianBlock; ++k) {
632 gc_red.add(grad_coeff_pkt[p].sum(k));
633 gc_red.add(grad_coeff_pkt[p].err(k));
634 }
635 const double gc = gc_red.value();
636 const auto& pair = query[p];
637 hessian->local.push_back(gc * pair.hessian -
638 (2.0 * scalar_sum * inv_p[p]) *
639 pair.gradient *
640 pair.gradient.transpose());
641 hessian->translation_invariant =
642 hessian->translation_invariant && pair.second < dof / 3;
643 }
644 return hessian;
645 }
646
647 std::vector<linalg::CompensatedSum> gradient_coeff(query.size());
648 hessian->u = Eigen::MatrixXd::Zero(n, dof);
649 hessian->v = Eigen::MatrixXd::Zero(n, dof);
650 hessian->kernel.resize(n);
651 hessian->weighted_scalar.resize(n);
652 linalg::CompensatedSum scalar_sum;
653 for (Eigen::Index i = 0; i < n; ++i) {
654 const auto& row = basis.cutoff_rows[i];
655 linalg::CompensatedSum distance;
657 scalar.add(basis.energy_weights(i));
658 forEachPairUnion(
659 row, query,
660 [&](const CutoffTrainPair* a, const CutoffPairFeature* b) {
661 const double inverse = inverse_length(a ? a->type : b->type);
662 const double delta =
663 (a ? a->value : 0.0) - (b ? b->value : 0.0);
664 const double c = a ? a->contraction : 0.0;
665 distance.add(inverse * delta * delta);
666 scalar.add(-2.0 * inverse * delta * c);
667 if (!b) return;
668 const Eigen::Vector3d u = (2.0 * inverse * delta) * b->gradient;
669 const Eigen::Vector3d v = (2.0 * inverse * c) * b->gradient;
670 hessian->u.block<1, 3>(i, 3 * b->first) += u.transpose();
671 hessian->v.block<1, 3>(i, 3 * b->first) += v.transpose();
672 if (b->second < dof / 3) {
673 hessian->u.block<1, 3>(i, 3 * b->second) -= u.transpose();
674 hessian->v.block<1, 3>(i, 3 * b->second) -= v.transpose();
675 }
676 });
677 const double dist_val = distance.value();
678 const double scalar_val = scalar.value();
679 const double kernel =
680 primitive.getMagnSigma2() * numerics::exp(-dist_val);
681 hessian->kernel(i) = kernel;
682 hessian->weighted_scalar(i) = kernel * scalar_val;
683 scalar_sum.add(kernel * scalar_val);
684 forEachPairUnion(
685 row, query,
686 [&](const CutoffTrainPair* a, const CutoffPairFeature* b) {
687 if (!b) return;
688 const auto p = static_cast<std::size_t>(b - query.data());
689 const double inverse = inverse_length(b->type);
690 const double delta = (a ? a->value : 0.0) - b->value;
691 const double c = a ? a->contraction : 0.0;
692 const double factor = 2.0 * inverse * kernel;
693 gradient_coeff[p].add(factor * (delta * scalar_val + c));
694 });
695 }
696 const double total_scalar = scalar_sum.value();
697 hessian->local.reserve(query.size());
698 for (std::size_t p = 0; p < query.size(); ++p) {
699 const auto& pair = query[p];
700 hessian->local.push_back(
701 gradient_coeff[p].value() * pair.hessian -
702 (2.0 * total_scalar * inverse_length(pair.type)) * pair.gradient *
703 pair.gradient.transpose());
704 hessian->translation_invariant =
705 hessian->translation_invariant && pair.second < dof / 3;
706 }
707 return hessian;
708}
709
710bool applySexpatMeanHessianDouble(const SexpatMeanHessianDouble& hessian,
711 Eigen::Index dof,
712 const Eigen::VectorXd& direction,
713 Eigen::VectorXd& action)
714{
715 if (direction.size() != dof || !direction.allFinite()) return false;
716 Eigen::VectorXd velocity = direction;
717 // Relative velocities preserve the exact translation nullspace
718 // even when fitted Hermite coefficients strongly cancel.
719 if (hessian.translation_invariant) {
720 const Eigen::Vector3d reference = velocity.head<3>();
721 for (Eigen::Index atom = 0; atom < dof / 3; ++atom)
722 velocity.segment<3>(3 * atom) -= reference;
723 }
724 const Eigen::VectorXd ud = hessian.u * velocity;
725 const Eigen::VectorXd vd = hessian.v * velocity;
726 const Eigen::VectorXd left = (hessian.weighted_scalar.array() * ud.array() +
727 hessian.kernel.array() * vd.array())
728 .matrix();
729 const Eigen::VectorXd right =
730 (hessian.kernel.array() * ud.array()).matrix();
731 action.noalias() = hessian.u.transpose() * left;
732 action.noalias() += hessian.v.transpose() * right;
733 for (std::size_t p = 0; p < hessian.pairs.size(); ++p) {
734 const auto& pair = hessian.pairs[p];
735 Eigen::Vector3d relative = velocity.segment<3>(3 * pair.first);
736 if (pair.second < dof / 3)
737 relative -= velocity.segment<3>(3 * pair.second);
738 const Eigen::Vector3d contribution = hessian.local[p] * relative;
739 action.segment<3>(3 * pair.first) += contribution;
740 if (pair.second < dof / 3)
741 action.segment<3>(3 * pair.second) -= contribution;
742 }
743 return action.allFinite();
744}
745
746bool assembleSexpatMeanHessianDouble(const SexpatMeanHessianDouble& hessian,
747 Eigen::Index dof, Eigen::MatrixXd& result)
748{
749 const Eigen::MatrixXd left =
750 hessian.weighted_scalar.asDiagonal() * hessian.u +
751 hessian.kernel.asDiagonal() * hessian.v;
752 result.noalias() = hessian.u.transpose() * left;
753 result.noalias() +=
754 hessian.v.transpose() * (hessian.kernel.asDiagonal() * hessian.u);
755 for (std::size_t p = 0; p < hessian.pairs.size(); ++p) {
756 const auto& pair = hessian.pairs[p];
757 const Eigen::Matrix3d& block = hessian.local[p];
758 const Eigen::Index a = 3 * pair.first, b = 3 * pair.second;
759 result.block<3, 3>(a, a) += block;
760 if (pair.second < dof / 3) {
761 result.block<3, 3>(a, b) -= block;
762 result.block<3, 3>(b, a) -= block;
763 result.block<3, 3>(b, b) += block;
764 }
765 }
766 // The action applies H to velocities relative to the first atom; the
767 // dense columns are H (I - E_0) for the same exact translation nullspace.
768 if (hessian.translation_invariant) {
769 Eigen::MatrixXd translation = Eigen::MatrixXd::Zero(dof, 3);
770 for (Eigen::Index atom = 0; atom < dof / 3; ++atom)
771 translation += result.middleCols(3 * atom, 3);
772 result.leftCols(3) -= translation;
773 }
774 return result.allFinite();
775}
776
777std::shared_ptr<const SexpatMeanBasisLong> prepareSexpatMeanBasisLong(
778 const SexpatCF& source, const Eigen::MatrixXd& training,
779 const Eigen::VectorXd& weights)
780{
781 if (!validSexpatHessianInputs(source, training, weights)) return nullptr;
782 const Eigen::Index n = training.rows(), dof = training.cols();
783 auto primitive = std::make_shared<SexpatCF>(source);
784 primitive->clearDistanceCache();
785 auto basis = std::make_shared<SexpatMeanBasisLong>();
786 basis->n = n;
787 basis->dof = dof;
788 basis->rows = radialPairFeatures(training, primitive->getConfInfo(),
789 primitive->farFieldRadius());
790 const auto& lengths = primitive->getAtomisticLengthScaleRef();
791 basis->energy_weights = weights.head(n);
792 basis->gradient_weights.resize(n);
793 for (Eigen::Index i = 0; i < n; ++i) {
794 auto& contractions = basis->gradient_weights[i];
795 for (const auto& pair: basis->rows[i]) {
796 if (pair.type < 0 ||
797 (lengths.size() != 1 && pair.type >= lengths.size()))
798 return nullptr;
799 long double contraction = 0.0L;
800 for (Eigen::Index d = 0; d < 3; ++d) {
801 const long double first =
802 weights((3 * pair.first + d + 1) * n + i);
803 const long double second =
804 pair.second < dof / 3
805 ? weights((3 * pair.second + d + 1) * n + i)
806 : 0.0L;
807 contraction += (first - second) * pair.gradient(d);
808 }
809 contractions.push_back(contraction);
810 }
811 }
812 basis->primitive = std::move(primitive);
813 return basis;
814}
815
816std::shared_ptr<const SexpatMeanHessianLong> prepareSexpatMeanHessianLong(
817 const SexpatMeanBasisLong& basis, const Eigen::VectorXd& position)
818{
819 const Eigen::Index n = basis.n, dof = basis.dof;
820 if (position.size() != dof || !position.allFinite()) return nullptr;
821 const SexpatCF& primitive = *basis.primitive;
822 const Coord query_position = position.transpose();
823 auto hessian = std::make_shared<SexpatMeanHessianLong>();
824 hessian->pairs = radialPairFeatures(query_position, primitive.getConfInfo(),
825 primitive.farFieldRadius())
826 .front();
827 const auto& query = hessian->pairs;
828 // The energy and gradient kernel contracts with the atomistic pair
829 // length. getLengthScaleRef() is the chart length once a manifold
830 // chart is fitted, and that scale is not this kernel.
831 const auto& lengths = primitive.getAtomisticLengthScaleRef();
832 for (const auto& pair: query) {
833 if (pair.type < 0 ||
834 (lengths.size() != 1 && pair.type >= lengths.size()))
835 return nullptr;
836 }
837 std::vector<long double> gradient_coeff(query.size(), 0.0L);
838 hessian->u = LongMatrix::Zero(n, dof);
839 hessian->v = LongMatrix::Zero(n, dof);
840 hessian->kernel.resize(n);
841 hessian->weighted_scalar.resize(n);
842 long double scalar_sum = 0.0L;
843 const auto inverse_length = [&](Eigen::Index type) -> long double {
844 const long double length =
845 lengths.data()[lengths.size() == 1 ? 0 : type];
846 return 1.0L / (length * length);
847 };
848 for (Eigen::Index i = 0; i < n; ++i) {
849 const auto& row = basis.rows[i];
850 const auto& contractions = basis.gradient_weights[i];
851 long double distance = 0.0L, scalar = basis.energy_weights(i);
853 row, query,
854 [&](const CutoffPairFeature* a, const CutoffPairFeature* b) {
855 const long double inverse =
856 inverse_length(a ? a->type : b->type);
857 const long double delta =
858 (a ? a->value : 0.0L) - (b ? b->value : 0.0L);
859 const long double c = a ? contractions[a - row.data()] : 0.0L;
860 distance += inverse * delta * delta;
861 scalar -= 2.0L * inverse * delta * c;
862 if (!b) return;
863 const LongVector3 u =
864 (2.0L * inverse * delta) * b->gradient.cast<long double>();
865 const LongVector3 v =
866 (2.0L * inverse * c) * b->gradient.cast<long double>();
867 hessian->u.block<1, 3>(i, 3 * b->first) += u.transpose();
868 hessian->v.block<1, 3>(i, 3 * b->first) += v.transpose();
869 if (b->second < dof / 3) {
870 hessian->u.block<1, 3>(i, 3 * b->second) -= u.transpose();
871 hessian->v.block<1, 3>(i, 3 * b->second) -= v.transpose();
872 }
873 });
874 const long double kernel =
875 primitive.getMagnSigma2() * numerics::exp(-distance);
876 hessian->kernel(i) = kernel;
877 hessian->weighted_scalar(i) = kernel * scalar;
878 scalar_sum += kernel * scalar;
880 row, query,
881 [&](const CutoffPairFeature* a, const CutoffPairFeature* b) {
882 if (!b) return;
883 const auto p = b - query.data();
884 const long double inverse = inverse_length(b->type);
885 const long double delta = (a ? a->value : 0.0L) - b->value;
886 const long double c = a ? contractions[a - row.data()] : 0.0L;
887 const long double factor = 2.0L * inverse * kernel;
888 gradient_coeff[p] += factor * (delta * scalar + c);
889 });
890 }
891 for (std::size_t p = 0; p < query.size(); ++p) {
892 const auto& pair = query[p];
893 hessian->local.push_back(
894 gradient_coeff[p] * pair.hessian.cast<long double>() -
895 (2.0L * scalar_sum * inverse_length(pair.type)) *
896 pair.gradient.cast<long double>() *
897 pair.gradient.cast<long double>().transpose());
898 hessian->translation_invariant =
899 hessian->translation_invariant && pair.second < dof / 3;
900 }
901 return hessian;
902}
903
904bool applySexpatMeanHessianLong(const SexpatMeanHessianLong& hessian,
905 Eigen::Index dof,
906 const Eigen::VectorXd& direction,
907 Eigen::VectorXd& action)
908{
909 if (direction.size() != dof || !direction.allFinite()) return false;
910 LongVector velocity = direction.cast<long double>();
911 // Relative velocities preserve the exact translation nullspace
912 // even when fitted Hermite coefficients strongly cancel.
913 if (hessian.translation_invariant) {
914 const LongVector3 reference = velocity.head<3>();
915 for (Eigen::Index atom = 0; atom < dof / 3; ++atom)
916 velocity.segment<3>(3 * atom) -= reference;
917 }
918 const LongVector ud = hessian.u * velocity;
919 const LongVector vd = hessian.v * velocity;
920 const LongVector left = (hessian.weighted_scalar.array() * ud.array() +
921 hessian.kernel.array() * vd.array())
922 .matrix();
923 const LongVector right = (hessian.kernel.array() * ud.array()).matrix();
924 LongVector result =
925 hessian.u.transpose() * left + hessian.v.transpose() * right;
926 for (std::size_t p = 0; p < hessian.pairs.size(); ++p) {
927 const auto& pair = hessian.pairs[p];
928 LongVector3 relative = velocity.segment<3>(3 * pair.first);
929 if (pair.second < dof / 3)
930 relative -= velocity.segment<3>(3 * pair.second);
931 const LongVector3 contribution = hessian.local[p] * relative;
932 result.segment<3>(3 * pair.first) += contribution;
933 if (pair.second < dof / 3)
934 result.segment<3>(3 * pair.second) -= contribution;
935 }
936 action = result.cast<double>();
937 return action.allFinite();
938}
939
940bool assembleSexpatMeanHessianLong(const SexpatMeanHessianLong& hessian,
941 Eigen::Index dof, Eigen::MatrixXd& result)
942{
943 const Eigen::MatrixXd u = hessian.u.cast<double>();
944 const Eigen::MatrixXd v = hessian.v.cast<double>();
945 const Eigen::VectorXd kernel = hessian.kernel.cast<double>();
946 const Eigen::VectorXd scalar = hessian.weighted_scalar.cast<double>();
947 const Eigen::MatrixXd left =
948 scalar.asDiagonal() * u + kernel.asDiagonal() * v;
949 result.noalias() = u.transpose() * left;
950 result.noalias() += v.transpose() * (kernel.asDiagonal() * u);
951 for (std::size_t p = 0; p < hessian.pairs.size(); ++p) {
952 const auto& pair = hessian.pairs[p];
953 const Eigen::Matrix3d block = hessian.local[p].cast<double>();
954 const Eigen::Index a = 3 * pair.first, b = 3 * pair.second;
955 result.block<3, 3>(a, a) += block;
956 if (pair.second < dof / 3) {
957 result.block<3, 3>(a, b) -= block;
958 result.block<3, 3>(b, a) -= block;
959 result.block<3, 3>(b, b) += block;
960 }
961 }
962 // The action applies H to velocities relative to the first atom; the
963 // dense columns are H (I - E_0) for the same exact translation nullspace.
964 if (hessian.translation_invariant) {
965 Eigen::MatrixXd translation = Eigen::MatrixXd::Zero(dof, 3);
966 for (Eigen::Index atom = 0; atom < dof / 3; ++atom)
967 translation += result.middleCols(3 * atom, 3);
968 result.leftCols(3) -= translation;
969 }
970 return result.allFinite();
971}
972
973} // namespace
974
976 const Eigen::MatrixXd& training, const Eigen::VectorXd& weights) const
977{
978 if (hessian_precision_ != HessianPrecision::Double &&
979 hessian_precision_ != HessianPrecision::LongDouble)
980 return {};
981 if (primitive_->getMagnSigma2() == 0.0)
982 return validSexpatHessianInputs(*primitive_, training, weights)
983 ? zeroSexpatMeanHessianMatrix(training.cols())
985 if (hessian_precision_ == HessianPrecision::Double) {
986 auto basis =
987 prepareSexpatMeanBasisDouble(*primitive_, training, weights);
988 if (!basis) return {};
989 return [basis = std::move(basis)](const Eigen::VectorXd& position,
990 Eigen::MatrixXd& hessian) {
991 const auto prepared =
992 prepareSexpatMeanHessianDouble(*basis, position);
993 return prepared && assembleSexpatMeanHessianDouble(
994 *prepared, basis->dof, hessian);
995 };
996 }
997 if (hessian_precision_ == HessianPrecision::LongDouble) {
998 auto basis = prepareSexpatMeanBasisLong(*primitive_, training, weights);
999 if (!basis) return {};
1000 return [basis = std::move(basis)](const Eigen::VectorXd& position,
1001 Eigen::MatrixXd& hessian) {
1002 const auto prepared =
1003 prepareSexpatMeanHessianLong(*basis, position);
1004 return prepared && assembleSexpatMeanHessianLong(
1005 *prepared, basis->dof, hessian);
1006 };
1007 }
1008 return {};
1009}
1010
1012 const Eigen::MatrixXd& training, const Eigen::VectorXd& weights) const
1013{
1014 if (hessian_precision_ != HessianPrecision::Double &&
1015 hessian_precision_ != HessianPrecision::LongDouble)
1016 return {};
1017 if (primitive_->getMagnSigma2() == 0.0)
1018 return validSexpatHessianInputs(*primitive_, training, weights)
1019 ? zeroSexpatMeanHessian(training.cols())
1021 if (hessian_precision_ == HessianPrecision::Double) {
1022 auto basis =
1023 prepareSexpatMeanBasisDouble(*primitive_, training, weights);
1024 if (!basis) return {};
1025 return [basis = std::move(basis)](
1026 const Eigen::VectorXd& position) -> HessianAction {
1027 auto hessian = prepareSexpatMeanHessianDouble(*basis, position);
1028 if (!hessian) return {};
1029 return
1030 [hessian = std::move(hessian), dof = basis->dof](
1031 const Eigen::VectorXd& direction, Eigen::VectorXd& action) {
1032 return applySexpatMeanHessianDouble(*hessian, dof,
1033 direction, action);
1034 };
1035 };
1036 }
1037 if (hessian_precision_ == HessianPrecision::LongDouble) {
1038 auto basis = prepareSexpatMeanBasisLong(*primitive_, training, weights);
1039 if (!basis) return {};
1040 return [basis = std::move(basis)](
1041 const Eigen::VectorXd& position) -> HessianAction {
1042 auto hessian = prepareSexpatMeanHessianLong(*basis, position);
1043 if (!hessian) return {};
1044 return
1045 [hessian = std::move(hessian), dof = basis->dof](
1046 const Eigen::VectorXd& direction, Eigen::VectorXd& action) {
1047 return applySexpatMeanHessianLong(*hessian, dof, direction,
1048 action);
1049 };
1050 };
1051 }
1052 return {};
1053}
1054
1056 const Eigen::MatrixXd& training, const Eigen::VectorXd& weights) const
1057{
1058 const Eigen::Index dof = 3 * primitive_->conf_info.atoms_mov.type.size();
1059 const Eigen::Index count = training.rows();
1060 if (dof <= 0 || training.cols() != dof || !training.allFinite() ||
1061 weights.size() != count * (dof + 1) || !weights.allFinite())
1062 throw std::invalid_argument("invalid Sexpat mean coefficients");
1063 const auto& lengths = primitive_->lengthScale;
1064 if ((lengths.size() != 1 && lengths.size() != primitive_->conf_info.n_pt) ||
1065 !(lengths.array() > 0.0).all())
1066 throw std::invalid_argument("Sexpat mean requires positive lengths");
1067 auto primitive = std::make_shared<SexpatCF>(*primitive_);
1068 primitive->clearDistanceCache();
1069 auto kernel = std::make_shared<const Sexpat>(std::move(primitive));
1070 auto prepared = std::make_shared<PreparedAlphaK>();
1071 if (count > 0 && !kernel->prepareAlphaK(training, weights.head(count),
1072 weights, *prepared)) {
1073 return [kernel, training,
1074 weights](const Eigen::MatrixXd& query) -> Eigen::VectorXd {
1075 return kernel->KernelOperator::applyJointCrossCovariance(
1076 query, training, weights);
1077 };
1078 }
1079 return [kernel,
1080 prepared =
1081 std::shared_ptr<const PreparedAlphaK>(std::move(prepared)),
1082 dof, count](const Eigen::MatrixXd& query) -> Eigen::VectorXd {
1083 if (query.cols() != dof || !query.allFinite())
1084 throw std::invalid_argument("invalid Sexpat mean query");
1085 const Eigen::Index rows = query.rows();
1086 Eigen::VectorXd result = Eigen::VectorXd::Zero(rows * (dof + 1));
1087 if (rows == 0 || count == 0) return result;
1088 Eigen::VectorXd energy = Eigen::VectorXd::Zero(rows);
1089 Coord gradient = Coord::Zero(rows, dof);
1090 kernel->predictMeanAlphaKPrepared(*prepared, query, energy, gradient);
1091 result.head(rows) = energy;
1092 for (Eigen::Index d = 0; d < dof; ++d)
1093 result.segment((d + 1) * rows, rows) = gradient.col(d);
1094 return result;
1095 };
1096}
1097
1099 const Eigen::MatrixXd& left_positions,
1100 const Eigen::MatrixXd& right_positions,
1101 const Eigen::VectorXd& weights) const
1102{
1103 const Eigen::Index dof = 3 * primitive_->conf_info.atoms_mov.type.size();
1104 const Eigen::Index nl = left_positions.rows(), nr = right_positions.rows();
1105 if (dof <= 0 || left_positions.cols() != dof ||
1106 right_positions.cols() != dof || !left_positions.allFinite() ||
1107 !right_positions.allFinite() || weights.size() != nr * (dof + 1) ||
1108 !weights.allFinite())
1109 throw std::invalid_argument("invalid Sexpat covariance product inputs");
1110 const auto& lengths = primitive_->lengthScale;
1111 if ((lengths.size() != 1 && lengths.size() != primitive_->conf_info.n_pt) ||
1112 !(lengths.array() > 0.0).all())
1113 throw std::invalid_argument(
1114 "Sexpat covariance product requires positive lengths");
1115 Eigen::VectorXd result = Eigen::VectorXd::Zero(nl * (dof + 1));
1116 if (nl == 0 || nr == 0) return result;
1117 const Coord training = right_positions, query = left_positions;
1118 PreparedAlphaK prepared;
1119 if (!prepareAlphaK(training, weights.head(nr), weights, prepared))
1121 left_positions, right_positions, weights);
1122 Eigen::VectorXd energy = Eigen::VectorXd::Zero(nl);
1123 Coord gradient = Coord::Zero(nl, dof);
1124 predictMeanAlphaKPrepared(prepared, query, energy, gradient);
1125 result.head(nl) = energy;
1126 for (Eigen::Index d = 0; d < dof; ++d)
1127 result.segment((d + 1) * nl, nl) = gradient.col(d);
1128 return result;
1129}
1130
1132 const Coord& x_train, const Coord& x_test,
1133 const Eigen::Ref<const Eigen::VectorXd>& alpha_E,
1134 const Eigen::Ref<const Eigen::VectorXd>& alpha_G_flat,
1135 Eigen::Ref<Eigen::VectorXd> mu_E_out,
1136 Eigen::Ref<
1137 Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>>
1138 mu_G_out) const
1139{
1140 PreparedAlphaK prepared;
1141 if (!prepareAlphaK(x_train, alpha_E, alpha_G_flat, prepared)) return;
1142 predictMeanAlphaKPrepared(prepared, x_test, mu_E_out, mu_G_out);
1143}
1144
1146 const Coord& x_train, const Eigen::Ref<const Eigen::VectorXd>& alpha_E,
1147 const Eigen::Ref<const Eigen::VectorXd>& alpha_G_flat,
1148 PreparedAlphaK& prepared) const
1149{
1150 const auto& conf_info = primitive_->conf_info;
1151 const auto& lengthScale = primitive_->lengthScale;
1152 prepared = PreparedAlphaK{};
1153 const Eigen::Index num_train = x_train.rows();
1154 if (num_train == 0 || alpha_G_flat.size() % num_train != 0) return false;
1155 const Eigen::Index dof = alpha_G_flat.size() / num_train - 1;
1156 if (dof <= 0 || x_train.cols() < dof) return false;
1157 if (alpha_E.size() < num_train ||
1158 alpha_G_flat.size() < num_train * (dof + 1))
1159 return false;
1160
1161 if (conf_info.pair_cutoff > 0.0 || primitive_->farFieldRadius() > 0.0) {
1162 prepared.num_train = num_train;
1163 prepared.dof = dof;
1164 prepared.alpha_E.assign(alpha_E.data(), alpha_E.data() + num_train);
1166 x_train.leftCols(dof), conf_info, primitive_->farFieldRadius());
1167 prepared.cutoff_gradient_weights.resize(num_train);
1168 for (Eigen::Index i = 0; i < num_train; ++i) {
1169 auto& weights = prepared.cutoff_gradient_weights[i];
1170 for (const auto& pair: prepared.cutoff_rows[i]) {
1171 linalg::CompensatedSum contraction;
1172 for (Eigen::Index dim = 0; dim < 3; ++dim) {
1173 const double first = alpha_G_flat(
1174 (3 * pair.first + dim + 1) * num_train + i);
1175 const double second =
1176 pair.second < dof / 3
1177 ? alpha_G_flat(
1178 (3 * pair.second + dim + 1) * num_train + i)
1179 : 0.0;
1180 contraction.addProduct(first - second, pair.gradient(dim));
1181 }
1182 weights.push_back(contraction.value());
1183 }
1184 }
1185 prepared.valid = true;
1186 return true;
1187 }
1188
1189 const Eigen::Index N_mov =
1190 static_cast<Eigen::Index>(conf_info.atoms_mov.type.cols());
1191 const Eigen::Index N_fro =
1192 static_cast<Eigen::Index>(conf_info.atoms_froz_active.type.cols());
1193
1194 // Enumerate pairs (moving-moving + moving-frozen) and their pairtype +
1195 // atomic indices. Layout matches Distance::cacheInverseDistances:
1196 // triangular j<i over moving-moving, then moving x frozen.
1197 std::vector<AlphaKPairInfo> pairs;
1198 pairs.reserve(
1199 static_cast<size_t>((N_mov * (N_mov - 1)) / 2 + N_mov * N_fro));
1200
1201 const bool scalar_length = lengthScale.size() == 1;
1202 auto inv_l2_for_pairtype = [&](Index_t pt) {
1203 const double l =
1204 scalar_length ? lengthScale(0, 0) : *(lengthScale.data() + pt);
1205 return 1.0 / (l * l);
1206 };
1207 auto active_pairtype = [&](Index_t pt) {
1208 // Index_t is unsigned: `pt < 0` is dead and EMPTY (-1) arrives
1209 // as UINT32_MAX, which the equality catches.
1210 if (pt == static_cast<Index_t>(EMPTY)) return false;
1211 if (!scalar_length && pt >= lengthScale.size()) return false;
1212 if (conf_info.n_pt > 0 && pt >= conf_info.n_pt) return false;
1213 return true;
1214 };
1215
1216 if (N_mov > 1) {
1217 for (Eigen::Index j = 0; j < N_mov - 1; ++j) {
1218 for (Eigen::Index i = j + 1; i < N_mov; ++i) {
1219 const Index_t pt =
1220 conf_info.pairtype(conf_info.atoms_mov.type(0, i),
1221 conf_info.atoms_mov.type(0, j));
1222 if (!active_pairtype(pt)) continue;
1223 pairs.push_back(AlphaKPairInfo{
1224 i, j, false, inv_l2_for_pairtype(pt),
1225 scalar_length ? 0 : static_cast<Eigen::Index>(pt)});
1226 }
1227 }
1228 }
1229 if (N_fro > 0) {
1230 for (Eigen::Index j = 0; j < N_mov; ++j) {
1231 for (Eigen::Index i = 0; i < N_fro; ++i) {
1232 const Index_t pt =
1233 conf_info.pairtype(conf_info.atoms_froz_active.type(0, i),
1234 conf_info.atoms_mov.type(0, j));
1235 if (!active_pairtype(pt)) continue;
1236 pairs.push_back(AlphaKPairInfo{
1237 j, i, true, inv_l2_for_pairtype(pt),
1238 scalar_length ? 0 : static_cast<Eigen::Index>(pt)});
1239 }
1240 }
1241 }
1242
1243 const Eigen::Index n_pairs = static_cast<Eigen::Index>(pairs.size());
1244 if (n_pairs == 0) return false;
1245
1246 // Storage layout: row-major-of-packed-3D, mirrors aux::Distance.
1247 const double* const x_train_data = x_train.data();
1248 const Eigen::Index x_train_cols = x_train.cols();
1249 const double* const froz_data =
1250 conf_info.atoms_froz_active.positions.data();
1251 const geometry::PairBox box(conf_info.cell);
1252
1253 // Per-test-point work. For each (m, i, p) we update:
1254 // k_i_m, scalar_i_m, A_p[m]
1255 // then per d_test_atomic = (atom, xyz) we collect mu_G[m, d].
1256 //
1257 // alpha_G_flat layout: alpha_G_flat[d_global * num_train + i] where
1258 // d_global is the 1-based atomic-coord index per SexpAt convention:
1259 // d_global = atom_a * 3 + xyz + 1 (atom_a in 0..N_mov-1; xyz in 0..2)
1260 // d_global == 0 is reserved for alpha_E (handled separately).
1261 auto alpha_G_at = [&](Eigen::Index atom_a, int xyz,
1262 Eigen::Index i) -> double {
1263 const Eigen::Index d_global = atom_a * 3 + xyz + 1;
1264 const Eigen::Index idx = d_global * num_train + i;
1265 if (idx < 0 || idx >= alpha_G_flat.size()) return 0.0;
1266 return alpha_G_flat(idx);
1267 };
1268
1269 // Per-pair x_train side scratch, stored train-point major:
1270 // inv_r_train[i * n_pairs + p] = 1 / ||x_train[i, a] - x_train[i, b]
1271 // (or frozen)||
1272 // c_p_train[i * n_pairs + p] = (alpha_G_a - alpha_G_b) dot du/dx_a
1273 // Frozen atoms have zero force-observation weight.
1274 //
1275 // The prediction hot loop walks p innermost for a fixed train point i, so
1276 // point-major keeps that walk contiguous. This fill is the transposed
1277 // access, run once per model refresh against once per predicted point.
1278 prepared.inv_r_train.assign(static_cast<size_t>(n_pairs * num_train), 0.0);
1279 prepared.c_p_train.assign(static_cast<size_t>(n_pairs * num_train), 0.0);
1280 double* const invr_base = prepared.inv_r_train.data();
1281 double* const cp_base = prepared.c_p_train.data();
1282
1283 for (Eigen::Index p = 0; p < n_pairs; ++p) {
1284 const AlphaKPairInfo& pinfo = pairs[static_cast<size_t>(p)];
1285 const Eigen::Index off_a = 3 * pinfo.atom_a;
1286 const Eigen::Index off_b = 3 * pinfo.atom_b;
1287
1288 for (Eigen::Index i = 0; i < num_train; ++i) {
1289 const size_t slot = static_cast<size_t>(i * n_pairs + p);
1290 const double* pa = x_train_data + i * x_train_cols + off_a;
1291 double bx, by, bz;
1292 if (pinfo.is_frozen) {
1293 const double* pf = froz_data + 3 * pinfo.atom_b;
1294 bx = pf[0];
1295 by = pf[1];
1296 bz = pf[2];
1297 } else {
1298 const double* pb = x_train_data + i * x_train_cols + off_b;
1299 bx = pb[0];
1300 by = pb[1];
1301 bz = pb[2];
1302 }
1303 const double bpos[3] = {bx, by, bz};
1304 double dr[3];
1305 box.displacement(bpos, pa, dr);
1306 const double dx = dr[0];
1307 const double dy = dr[1];
1308 const double dz = dr[2];
1309 const double r2 = dx * dx + dy * dy + dz * dz;
1310 const double r = std::sqrt(r2);
1311 const double inv_r = 1.0 / r;
1312 invr_base[slot] = inv_r;
1313 const double inv_r3 = inv_r * inv_r * inv_r;
1314 // du/dx_a = -(x_a - x_b) * inv_r3
1315 const double da[3] = {-dx * inv_r3, -dy * inv_r3, -dz * inv_r3};
1316 linalg::CompensatedSum contraction;
1317 for (int dim = 0; dim < 3; ++dim) {
1318 // Pair derivatives have opposite signs on movable atoms.
1319 // Subtract their weights before contracting so a uniform
1320 // Cartesian translation remains an exact null mode.
1321 const double difference =
1322 alpha_G_at(pinfo.atom_a, dim, i) -
1323 (pinfo.is_frozen ? 0.0 : alpha_G_at(pinfo.atom_b, dim, i));
1324 contraction.addProduct(difference, da[dim]);
1325 }
1326 cp_base[slot] = contraction.value();
1327 }
1328 }
1329
1330 prepared.num_train = num_train;
1331 prepared.dof = dof;
1332 prepared.pairs = std::move(pairs);
1333 prepared.alpha_E.assign(alpha_E.data(), alpha_E.data() + num_train);
1334 prepared.valid = true;
1335 return true;
1336}
1337
1339 const PreparedAlphaK& prepared, const Coord& x_test,
1340 Eigen::Ref<Eigen::VectorXd> mu_E_out,
1341 Eigen::Ref<
1342 Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>>
1343 mu_G_out) const
1344{
1345 const auto& conf_info = primitive_->conf_info;
1346 const double magnSigma2 = primitive_->magnSigma2;
1347 // Per-pair alpha-K predict (Schmitz/Chmiela JPCL 2022 eq.6).
1348 // For each test point m, accumulate:
1349 // mu_E[m] += Sum_i k_i_m * scalar_i_m
1350 // mu_G[m, b] += 2 * Sum_p touching b of (1/l_p^2) *
1351 // (dv_p/dx_m^b) * A_p_m
1352 if (!prepared.valid || prepared.num_train <= 0 || prepared.dof <= 0 ||
1353 x_test.cols() != prepared.dof ||
1354 static_cast<Eigen::Index>(prepared.alpha_E.size()) < prepared.num_train)
1355 return;
1356
1357 const auto product_mode = linalg::productMode();
1358 if (!prepared.cutoff_rows.empty()) {
1359 if (mu_E_out.size() < x_test.rows() ||
1360 mu_G_out.rows() < x_test.rows() || mu_G_out.cols() < prepared.dof)
1361 throw std::invalid_argument(
1362 "cutoff prediction output has incompatible dimensions");
1363 const auto query =
1364 radialPairFeatures(x_test, conf_info, primitive_->farFieldRadius());
1365 const auto& lengths = primitive_->lengthScale;
1366 for (Eigen::Index m = 0; m < x_test.rows(); ++m) {
1367 std::vector<double> kernel_terms;
1368 std::vector<double> coefficient_terms;
1369 std::vector<linalg::PredictProduct> gradient(
1370 static_cast<size_t>(prepared.dof),
1371 linalg::PredictProduct(product_mode));
1372 for (Eigen::Index i = 0; i < prepared.num_train; ++i) {
1373 const auto& training = prepared.cutoff_rows[i];
1374 const auto& weights = prepared.cutoff_gradient_weights[i];
1375 const auto inverse_length_squared = [&](Eigen::Index type) {
1376 if (lengths.size() != 1 && type >= lengths.size())
1377 return 0.0;
1378 const double length =
1379 lengths.data()[lengths.size() == 1 ? 0 : type];
1380 return 1.0 / (length * length);
1381 };
1382 linalg::CompensatedSum distance, linear;
1384 training, query[m],
1385 [&](const CutoffPairFeature* a,
1386 const CutoffPairFeature* b) {
1387 const double inverse =
1388 inverse_length_squared(a ? a->type : b->type);
1389 const double delta =
1390 (a ? a->value : 0.0) - (b ? b->value : 0.0);
1391 const double weight =
1392 a ? weights[a - training.data()] : 0.0;
1393 distance.addProduct(inverse * delta, delta);
1394 linear.addProduct(2.0 * inverse * delta, weight);
1395 });
1396 const double kernel =
1397 magnSigma2 * numerics::exp(-distance.value());
1398 const double coefficient = prepared.alpha_E[i] - linear.value();
1399 kernel_terms.push_back(kernel);
1400 coefficient_terms.push_back(coefficient);
1402 training, query[m],
1403 [&](const CutoffPairFeature* a,
1404 const CutoffPairFeature* b) {
1405 if (!b) return;
1406 const double inverse = inverse_length_squared(b->type);
1407 const double delta = (a ? a->value : 0.0) - b->value;
1408 const double weight =
1409 a ? weights[a - training.data()] : 0.0;
1410 const double factor =
1411 2.0 * inverse * (delta * coefficient + weight);
1412 for (int xyz = 0; xyz < 3; ++xyz) {
1413 const double component = factor * b->gradient(xyz);
1414 gradient[3 * b->first + xyz].addProduct(kernel,
1415 component);
1416 if (b->second < prepared.dof / 3)
1417 gradient[3 * b->second + xyz].addProduct(
1418 kernel, -component);
1419 }
1420 });
1421 }
1422 if (!kernel_terms.empty()) {
1423 mu_E_out(m) += linalg::evaluateStoredProduct(
1424 kernel_terms.data(), coefficient_terms.data(),
1425 static_cast<int>(kernel_terms.size()), product_mode);
1426 }
1427 for (Eigen::Index d = 0; d < prepared.dof; ++d)
1428 mu_G_out(m, d) += gradient[d].value();
1429 }
1430 return;
1431 }
1432
1433 const Eigen::Index num_train = prepared.num_train;
1434 const Eigen::Index num_test = x_test.rows();
1435 const Eigen::Index n_pairs =
1436 static_cast<Eigen::Index>(prepared.pairs.size());
1437 if (num_test == 0 || n_pairs == 0 || mu_E_out.size() < num_test ||
1438 mu_G_out.rows() < num_test)
1439 return;
1440
1441 const double* const x_test_data = x_test.data();
1442 const Eigen::Index x_test_cols = x_test.cols();
1443 const double* const froz_data =
1444 conf_info.atoms_froz_active.positions.data();
1445 const geometry::PairBox box(conf_info.cell);
1446
1447 // Per-test-point loop.
1448 std::vector<double> inv_r_test(static_cast<size_t>(n_pairs));
1449 // Pair differences for one train point, shared by the two pair passes:
1450 // the second needs scalar_i, which only the first can finish.
1451 std::vector<double> uv_scratch(static_cast<size_t>(n_pairs));
1452 // A_p and mu_E sum k_i*scalar_i terms whose scalar_i carry max|alpha|~1e5
1453 // and cancel to an O(1) result (~6 digits). Compensated mode sums the
1454 // TwoProductFMA expansion exactly and rounds once, so a cancelled product
1455 // residual is still present at that rounding.
1456 std::vector<linalg::PredictProduct> A_p(
1457 static_cast<size_t>(n_pairs), linalg::PredictProduct(product_mode));
1458 std::vector<const linalg::PredictProduct*> product_batch;
1459 std::vector<double> batch_values;
1460 if (product_mode == linalg::ProductMode::KernelFloat) {
1461 product_batch.resize(A_p.size() + 1);
1462 for (size_t p = 0; p < A_p.size(); ++p)
1463 product_batch[p + 1] = &A_p[p];
1464 }
1465 std::vector<double> dv_test(static_cast<size_t>(n_pairs) * 6);
1466
1467 for (Eigen::Index m = 0; m < num_test; ++m) {
1468 // Per-pair v_p_m and dv_p/dx_test_m.
1469 for (Eigen::Index p = 0; p < n_pairs; ++p) {
1470 const AlphaKPairInfo& pinfo =
1471 prepared.pairs[static_cast<size_t>(p)];
1472 const Eigen::Index off_a = 3 * pinfo.atom_a;
1473 const Eigen::Index off_b = 3 * pinfo.atom_b;
1474 const double* pa = x_test_data + m * x_test_cols + off_a;
1475 double bx, by, bz;
1476 if (pinfo.is_frozen) {
1477 const double* pf = froz_data + 3 * pinfo.atom_b;
1478 bx = pf[0];
1479 by = pf[1];
1480 bz = pf[2];
1481 } else {
1482 const double* pb = x_test_data + m * x_test_cols + off_b;
1483 bx = pb[0];
1484 by = pb[1];
1485 bz = pb[2];
1486 }
1487 const double bpos[3] = {bx, by, bz};
1488 double dr[3];
1489 box.displacement(bpos, pa, dr);
1490 const double dx = dr[0];
1491 const double dy = dr[1];
1492 const double dz = dr[2];
1493 const double r = std::sqrt(dx * dx + dy * dy + dz * dz);
1494 const double inv_r = 1.0 / r;
1495 inv_r_test[static_cast<size_t>(p)] = inv_r;
1496 const double inv_r3 = inv_r * inv_r * inv_r;
1497 const Eigen::Index row6 = p * 6;
1498 dv_test[row6 + 0] = -dx * inv_r3;
1499 dv_test[row6 + 1] = -dy * inv_r3;
1500 dv_test[row6 + 2] = -dz * inv_r3;
1501 if (!pinfo.is_frozen) {
1502 dv_test[row6 + 3] = dx * inv_r3;
1503 dv_test[row6 + 4] = dy * inv_r3;
1504 dv_test[row6 + 5] = dz * inv_r3;
1505 }
1506 }
1507
1508 // Reset A_p for this test point.
1509 for (auto& value: A_p)
1510 value.clear();
1511
1512 linalg::PredictProduct mu_E_acc(product_mode);
1513 // Sum over training points.
1514 for (Eigen::Index i = 0; i < num_train; ++i) {
1515 // Compute dist_sq_i_m = 2 * Sum_p inv_l2_p * (u_p_i - v_p_m)^2
1516 // (matches dist_at_cached_sq convention) and k_i_m.
1517 double dist_sq = 0.0;
1518 // scalar_i = alpha_E[i] - 2*Sum_p inv_l2*uv*c cancels the large
1519 // alpha against the kernel-weighted gradient term; accumulate with
1520 // compensation so the cancelled low-order bits survive.
1521 CompSum scalar_acc;
1522 scalar_acc.add(prepared.alpha_E[static_cast<size_t>(i)]);
1523 // Row base for this train point; p is contiguous from here.
1524 const double* const invr_row =
1525 prepared.inv_r_train.data() + static_cast<size_t>(i * n_pairs);
1526 const double* const cp_row =
1527 prepared.c_p_train.data() + static_cast<size_t>(i * n_pairs);
1528 for (Eigen::Index p = 0; p < n_pairs; ++p) {
1529 const AlphaKPairInfo& pinfo =
1530 prepared.pairs[static_cast<size_t>(p)];
1531 const double uv = invr_row[static_cast<size_t>(p)] -
1532 inv_r_test[static_cast<size_t>(p)];
1533 // Held for the A_p pass below, which needs the same
1534 // difference once scalar_i is known.
1535 uv_scratch[static_cast<size_t>(p)] = uv;
1536 dist_sq += 2.0 * pinfo.inv_l2 * uv * uv;
1537 scalar_acc.add(-(2.0 * pinfo.inv_l2 * uv *
1538 cp_row[static_cast<size_t>(p)]));
1539 }
1540 const double scalar_i = scalar_acc.value();
1541 const double k_i_m = magnSigma2 * numerics::exp(-0.5 * dist_sq);
1542 mu_E_acc.addProduct(k_i_m, scalar_i);
1543
1544 // A_p[m] += k_i_m * [scalar_i * uv + c_p_train[i][p]]
1545 for (Eigen::Index p = 0; p < n_pairs; ++p) {
1546 A_p[static_cast<size_t>(p)].addProduct(
1547 k_i_m, scalar_i * uv_scratch[static_cast<size_t>(p)] +
1548 cp_row[static_cast<size_t>(p)]);
1549 }
1550 }
1551 if (product_mode == linalg::ProductMode::KernelFloat) {
1552 product_batch[0] = &mu_E_acc;
1554 batch_values);
1555 mu_E_out(m) += batch_values[0];
1556 } else {
1557 mu_E_out(m) += mu_E_acc.value();
1558 }
1559
1560 // Reduce per pair into mu_G_out(m, d_global) for each of the 6
1561 // (or 3 for moving-frozen) atomic-coord slots.
1562 // Note: d_global here is the 1-based atomic coord index; matches
1563 // the existing accumulator's pred_block = uDdim2[j] (1..D).
1564 // mu_G_out is sized num_test x D_global (where D_global == 3 * N_mov,
1565 // the max coord index uDdim2 can hit, indexed 0..D-1 by atomic
1566 // coord 1..D shifted down). The caller is responsible for the
1567 // mapping.
1568 const Eigen::Index n_g_cols = mu_G_out.cols();
1569 for (Eigen::Index p = 0; p < n_pairs; ++p) {
1570 const AlphaKPairInfo& pinfo =
1571 prepared.pairs[static_cast<size_t>(p)];
1572 const Eigen::Index row6 = p * 6;
1573 const double prefac =
1574 2.0 * pinfo.inv_l2 *
1575 (product_mode == linalg::ProductMode::KernelFloat
1576 ? batch_values[static_cast<size_t>(p) + 1]
1577 : A_p[static_cast<size_t>(p)].value());
1578 // atom_a slots
1579 for (int xyz = 0; xyz < 3; ++xyz) {
1580 const Eigen::Index d_global =
1581 pinfo.atom_a * 3 + xyz; // 0-based for mu_G_out columns
1582 if (d_global < n_g_cols) {
1583 mu_G_out(m, d_global) += prefac * dv_test[row6 + xyz];
1584 }
1585 }
1586 if (!pinfo.is_frozen) {
1587 for (int xyz = 0; xyz < 3; ++xyz) {
1588 const Eigen::Index d_global = pinfo.atom_b * 3 + xyz;
1589 if (d_global < n_g_cols) {
1590 mu_G_out(m, d_global) +=
1591 prefac * dv_test[row6 + 3 + xyz];
1592 }
1593 }
1594 }
1595 }
1596 }
1597}
1598
1600 const Coord& x_train, const Eigen::Ref<const Eigen::VectorXd>& alpha_E,
1601 const Eigen::Ref<const Eigen::VectorXd>& alpha_G_flat,
1602 Eigen::Ref<Eigen::VectorXd> quad_out, bool distributed,
1603 std::size_t* local_pair_count,
1604 const linalg::MpiContext* process_group) const
1605{
1606 const auto& lengthScale = primitive_->lengthScale;
1607 const double magnSigma2 = primitive_->magnSigma2;
1608 if (local_pair_count != nullptr) *local_pair_count = 0;
1609 const Eigen::Index n_hp = 1 + lengthScale.size();
1610 if (quad_out.size() < n_hp) return;
1611 PreparedAlphaK prepared;
1612 if (!prepareAlphaK(x_train, alpha_E, alpha_G_flat, prepared)) return;
1613 const Eigen::Index num_train = prepared.num_train;
1614 const auto& pairs = prepared.pairs;
1615 const Eigen::Index n_pairs = static_cast<Eigen::Index>(pairs.size());
1616
1618 Eigen::Index rank = 0, ranks = 1;
1620#ifdef GPR_LINALG_SCALAPACK
1621 if (distributed) {
1622 if (process_group != nullptr) {
1623 selected = *process_group;
1624 } else {
1625 auto& state = linalg::DistributedState::instance();
1626 state.initialize();
1627 selected = state.communication()->view();
1628 }
1629 rank = selected.rank;
1630 ranks = selected.nprocs;
1631 }
1632#else
1633 (void)distributed;
1634#endif
1635 std::vector<linalg::ExactSum> quadratic(n_hp);
1636 std::vector<Sum> distance(n_hp - 1), left_linear(n_hp - 1),
1637 right_linear(n_hp - 1), mixed(n_hp - 1);
1638 std::size_t evaluated_pairs = 0;
1639 for (Eigen::Index j = 0; j < num_train; ++j) {
1640 // Number the lower triangle consecutively. Cyclic ownership gives
1641 // every pair one owner and balances counts to within one pair.
1642 const Eigen::Index pair_offset = j * (j + 1) / 2;
1643 const Eigen::Index first = (rank + ranks - pair_offset % ranks) % ranks;
1644 for (Eigen::Index i = first; i <= j; i += ranks) {
1645 ++evaluated_pairs;
1646 std::fill(distance.begin(), distance.end(), Sum{});
1647 std::fill(left_linear.begin(), left_linear.end(), Sum{});
1648 std::fill(right_linear.begin(), right_linear.end(), Sum{});
1649 std::fill(mixed.begin(), mixed.end(), Sum{});
1650 const auto accumulate_pair = [&](Eigen::Index h, double inverse,
1651 double delta, double ci,
1652 double cj) {
1653 const double weighted_delta = 2.0 * inverse * delta;
1654 distance[h].addProduct(weighted_delta, delta);
1655 left_linear[h].addProduct(weighted_delta, ci);
1656 right_linear[h].addProduct(weighted_delta, cj);
1657 mixed[h].addProduct(2.0 * inverse * ci, cj);
1658 };
1659 if (!prepared.cutoff_rows.empty()) {
1660 const auto& left_row = prepared.cutoff_rows[i];
1661 const auto& right_row = prepared.cutoff_rows[j];
1663 left_row, right_row,
1664 [&](const CutoffPairFeature* a,
1665 const CutoffPairFeature* b) {
1666 const Eigen::Index type = a ? a->type : b->type;
1667 const Eigen::Index h =
1668 lengthScale.size() == 1 ? 0 : type;
1669 if (h >= lengthScale.size()) return;
1670 const double length = lengthScale.data()[h];
1671 const double delta =
1672 (a ? a->value : 0.0) - (b ? b->value : 0.0);
1673 const double ci =
1674 a ? prepared
1676 left_row.data()]
1677 : 0.0;
1678 const double cj = b ? prepared.cutoff_gradient_weights
1679 [j][b - right_row.data()]
1680 : 0.0;
1681 accumulate_pair(h, 1.0 / (length * length), delta, ci,
1682 cj);
1683 });
1684 } else {
1685 for (Eigen::Index p = 0; p < n_pairs; ++p) {
1686 const auto& pair = pairs[p];
1687 const auto left_slot = static_cast<size_t>(i * n_pairs + p);
1688 const auto right_slot =
1689 static_cast<size_t>(j * n_pairs + p);
1690 accumulate_pair(pair.length_index, pair.inv_l2,
1691 prepared.inv_r_train[left_slot] -
1692 prepared.inv_r_train[right_slot],
1693 prepared.c_p_train[left_slot],
1694 prepared.c_p_train[right_slot]);
1695 }
1696 }
1697 Sum exponent, left, right;
1698 left.add(alpha_E(i));
1699 right.add(alpha_E(j));
1700 for (Eigen::Index h = 0; h < n_hp - 1; ++h) {
1701 exponent.add(distance[h].sum);
1702 exponent.add(distance[h].corr);
1703 left.add(-left_linear[h].sum);
1704 left.add(-left_linear[h].corr);
1705 right.add(right_linear[h].sum);
1706 right.add(right_linear[h].corr);
1707 }
1708 const double ai = left.value();
1709 const double bj = right.value();
1710 Sum block;
1711 block.addProduct(ai, bj);
1712 for (const auto& term: mixed) {
1713 block.add(term.sum);
1714 block.add(term.corr);
1715 }
1716 // The two symmetric blocks share one contraction. The diagonal
1717 // contributes once and an off-diagonal block contributes twice.
1718 const double kernel = (i == j ? 1.0 : 2.0) * magnSigma2 *
1719 numerics::exp(-0.5 * exponent.value());
1720 quadratic[0].addProduct(kernel, block.sum);
1721 quadratic[0].addProduct(kernel, block.corr);
1722 for (Eigen::Index h = 0; h < n_hp - 1; ++h) {
1723 Sum derivative;
1724 derivative.addProduct(distance[h].value(), block.sum);
1725 derivative.addProduct(distance[h].value(), block.corr);
1726 derivative.addProduct(2.0 * left_linear[h].value(), bj);
1727 derivative.addProduct(-2.0 * right_linear[h].value(), ai);
1728 derivative.add(-2.0 * mixed[h].sum);
1729 derivative.add(-2.0 * mixed[h].corr);
1730 quadratic[h + 1].addProduct(kernel, derivative.sum);
1731 quadratic[h + 1].addProduct(kernel, derivative.corr);
1732 }
1733 }
1734 }
1735 if (local_pair_count != nullptr) *local_pair_count = evaluated_pairs;
1736#ifdef GPR_LINALG_SCALAPACK
1737 // Exact accumulators: the reduced value is the correctly rounded exact
1738 // sum, whatever the number of ranks that shared the pairs.
1739 if (ranks > 1)
1740 linalg::exact_sum_bcast(quadratic.data(), static_cast<int>(n_hp),
1741 selected);
1742#endif
1743 for (Eigen::Index h = 0; h < n_hp; ++h)
1744 quad_out(h) += quadratic[h].value();
1745}
1746
1747} // namespace gpr
Linear algebra abstraction layer for GPR hot-path operations.
@ x
Definition Enums.h:28
#define EMPTY
Definition Macros.h:39
std::function< bool(const Eigen::VectorXd &, Eigen::VectorXd &)> HessianAction
std::function< HessianAction(const Eigen::VectorXd &)> MeanHessianPreparation
std::function< bool( const Eigen::VectorXd &, const Eigen::VectorXd &, Eigen::VectorXd &)> MeanHessianFunction
std::function< Eigen::MatrixXd(Eigen::Index, Eigen::Index)> JointCovarianceTileFunction
std::function< Eigen::VectorXd(const Eigen::MatrixXd &)> MeanFunction
virtual Eigen::VectorXd applyJointCrossCovariance(const Eigen::MatrixXd &left_positions, const Eigen::MatrixXd &right_positions, const Eigen::VectorXd &weights) const
Pair-type inverse-distance squared-exponential primitive.
Definition SexpatCF.h:74
void trainingGradientAlphaK(const Coord &x_train, const Eigen::Ref< const Eigen::VectorXd > &alpha_E, const Eigen::Ref< const Eigen::VectorXd > &alpha_G_flat, Eigen::Ref< Eigen::VectorXd > quad_out, bool distributed=false, std::size_t *local_pair_count=nullptr, const linalg::MpiContext *process_group=nullptr) const
std::function< bool(const Eigen::VectorXd &, Eigen::MatrixXd &)> MeanHessianMatrixFunction
Eigen::VectorXd applyJointCrossCovariance(const Eigen::MatrixXd &left_positions, const Eigen::MatrixXd &right_positions, const Eigen::VectorXd &weights) const override
void predictMeanAlphaK(const Coord &x_train, const Coord &x_test, const Eigen::Ref< const Eigen::VectorXd > &alpha_E, const Eigen::Ref< const Eigen::VectorXd > &alpha_G_flat, Eigen::Ref< Eigen::VectorXd > mu_E_out, Eigen::Ref< Eigen::Matrix< double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor > > mu_G_out) const
Add the joint kernel action at query geometries to the output arrays.
bool prepareAlphaK(const Coord &x_train, const Eigen::Ref< const Eigen::VectorXd > &alpha_E, const Eigen::Ref< const Eigen::VectorXd > &alpha_G_flat, PreparedAlphaK &prepared) const
MeanFunction prepareMean(const Eigen::MatrixXd &training, const Eigen::VectorXd &weights) const override
Eigen::MatrixXd jointEnergyGradientCrossCovariance(const Eigen::MatrixXd &left_positions, const Eigen::MatrixXd &right_positions) const override
Assemble all Cartesian channels from one sparse pair walk per geometry.
MeanHessianFunction prepareMeanHessianVector(const Eigen::MatrixXd &training, const Eigen::VectorXd &weights) const override
MeanHessianMatrixFunction prepareMeanHessianMatrix(const Eigen::MatrixXd &training, const Eigen::VectorXd &weights) const
Dense Sexpat mean Hessian from two GEMMs and the pair blocks.
MeanHessianPreparation prepareMeanHessian(const Eigen::MatrixXd &training, const Eigen::VectorXd &weights) const override
JointCovarianceTileFunction prepareJointCovarianceTiles(const Eigen::MatrixXd &positions) const override
bool meanHessianVector(const Coord &training, const Eigen::VectorXd &weights, const Eigen::VectorXd &position, const Eigen::VectorXd &direction, Eigen::VectorXd &action) const override
void predictMeanAlphaKPrepared(const PreparedAlphaK &prepared, const Coord &x_test, Eigen::Ref< Eigen::VectorXd > mu_E_out, Eigen::Ref< Eigen::Matrix< double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor > > mu_G_out) const
Apply cached training weights with the same kernel parameters.
@ LongDouble
Extended-precision (long double) per-query setup.
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
static DistributedState & instance()
static void evaluateTogether(const std::vector< const PredictProduct * > &products, std::vector< double > &values)
void addProduct(double left, double right)
Eigen::MatrixXd Matrix
Eigen::VectorXd Vector
double evaluateStoredProduct(const double *left, const double *right, int length, ProductMode mode)
ProductMode productMode()
void exact_sum_bcast(ExactSum *sums, int count, const MpiContext &context)
double exp(double x) noexcept
Gaussian-process regression, kernels, priors, and the searches that run on the surrogate.
Definition Macros.h:16
void forEachCutoffPair(const CutoffPairFeatures &left, const CutoffPairFeatures &right, Function &&function)
Visit the union of two sparse feature rows in their common pair vocabulary.
Definition PairCutoff.h:105
FieldMatrixd Coord
Definition Macros.h:35
uint32_t Index_t
Definition Macros.h:17
std::vector< CutoffPairFeatures > radialPairFeatures(const Coord &positions, const AtomsConfiguration &configuration)
std::vector< CutoffPairFeature > CutoffPairFeatures
Definition PairCutoff.h:90
Eigen::Index second
Definition PairCutoff.h:75
Eigen::Vector3d gradient
Definition PairCutoff.h:78
std::vector< double > c_p_train
std::vector< double > alpha_E
std::vector< double > inv_r_train
std::vector< AlphaKPairInfo > pairs
std::vector< CutoffPairFeatures > cutoff_rows
std::vector< std::vector< double > > cutoff_gradient_weights
void addProduct(double left, double right)
static MpiContext local() noexcept
Definition MpiContext.h:75