Loading...
Searching...
No Matches
gpr::Sexpat Class Reference

#include <gpr/covariance_functions/KernelOperator.h>

Inheritance diagram for gpr::Sexpat:

Classes

struct  AlphaKPairInfo
struct  PreparedAlphaK

Public Types

enum class  HessianPrecision { Double , LongDouble }
using MeanHessianMatrixFunction
Public Types inherited from gpr::KernelOperator
enum class  MeanHessianStatus { Computed , Refused , Unavailable }
enum class  MeanCurvature { Unknown , Exact , Refused }
using MeanFunction = std::function<Eigen::VectorXd(const Eigen::MatrixXd&)>
using CrossCovarianceFunction
using JointCovarianceTileFunction
using MeanHessianFunction
using HessianAction
using MeanHessianPreparation
using MeanHessianMatrixFunction

Public Member Functions

 Sexpat (const SexpatCF &primitive)
 Sexpat (const SexpatCF &primitive, HessianPrecision precision)
 Sexpat (std::shared_ptr< const SexpatCF > primitive)
 Sexpat (std::shared_ptr< const SexpatCF > primitive, HessianPrecision precision)
void setHessianPrecision (HessianPrecision precision) noexcept
HessianPrecision hessianPrecision () const noexcept
void setUseLongDoubleHessian (bool enabled) noexcept
bool useLongDoubleHessian () const noexcept
JointCovarianceTileFunction prepareJointCovarianceTiles (const Eigen::MatrixXd &positions) const override
MeanFunction prepareMean (const Eigen::MatrixXd &training, const Eigen::VectorXd &weights) const override
MeanHessianFunction prepareMeanHessianVector (const Eigen::MatrixXd &training, const Eigen::VectorXd &weights) const override
MeanHessianPreparation prepareMeanHessian (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.
MeanCurvature meanCurvature () const noexcept override
bool meanHessianVector (const Coord &training, const Eigen::VectorXd &weights, const Eigen::VectorXd &position, const Eigen::VectorXd &direction, Eigen::VectorXd &action) const override
Eigen::VectorXd energyDiagonal (const Eigen::MatrixXd &positions) const override
 Energy self covariance at each geometry, without an all-pairs matrix.
Eigen::MatrixXd covarianceBlock (const Eigen::MatrixXd &left_positions, const Eigen::MatrixXd &right_positions, Eigen::Index left_channel, Eigen::Index right_channel) const override
 Covariance between one channel at each set of geometry rows.
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.
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
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.
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.
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
Public Member Functions inherited from gpr::KernelOperator
virtual ~KernelOperator ()=default
virtual CrossCovarianceFunction prepareCrossCovariance (const Eigen::MatrixXd &) const
Eigen::MatrixXd energyCorrelationDistances (const Eigen::MatrixXd &left_positions, const Eigen::MatrixXd &right_positions) const
virtual Eigen::MatrixXd jointEnergyGradientCovariance (const Eigen::MatrixXd &positions) const
 Joint covariance in Observation order [E; G_col0; ...; G_colD-1].
virtual Eigen::VectorXd jointEnergyGradientDiagonal (const Eigen::MatrixXd &positions) const
 Marginal prior variances in the same channel order as the joint matrix.

Detailed Description

Inverse-distance pair-type SE primitive as a KernelOperator summand.

This wraps SexpatCF's atomistic kernel only. Geodesic add and manifold dispatch are assembled outside Sexpat as Sum and Pullback.

Definition at line 387 of file KernelOperator.h.

Member Typedef Documentation

◆ MeanHessianMatrixFunction

Initial value:
std::function<bool(const Eigen::VectorXd&, Eigen::MatrixXd&)>

Definition at line 456 of file KernelOperator.h.

Member Enumeration Documentation

◆ HessianPrecision

enum class gpr::Sexpat::HessianPrecision
strong
Enumerator
Double 

Blocked compensated binary64 per-query setup. Preparation throws std::range_error when 2 / l^2 or a gradient-weight contraction is not representable in binary64.

LongDouble 

Extended-precision (long double) per-query setup.

Definition at line 409 of file KernelOperator.h.

409 {
413 Double,
414 LongDouble
415 };

Constructor & Destructor Documentation

◆ Sexpat() [1/4]

gpr::Sexpat::Sexpat ( const SexpatCF & primitive)
explicit

Definition at line 661 of file SexpatCF.cpp.

662 : Sexpat(primitive, primitive.hessianPrecision())
663{
664}
Sexpat(const SexpatCF &primitive)
Definition SexpatCF.cpp:661

◆ Sexpat() [2/4]

gpr::Sexpat::Sexpat ( const SexpatCF & primitive,
HessianPrecision precision )

Definition at line 666 of file SexpatCF.cpp.

667 : primitive_(&primitive), hessian_precision_(precision)
668{
669}

◆ Sexpat() [3/4]

gpr::Sexpat::Sexpat ( std::shared_ptr< const SexpatCF > primitive)
explicit

Definition at line 671 of file SexpatCF.cpp.

672 : owned_primitive_(std::move(primitive)),
673 primitive_(owned_primitive_.get()),
674 hessian_precision_(primitive_ ? primitive_->hessianPrecision()
676{
677 if (primitive_ == nullptr)
678 throw std::invalid_argument("Sexpat requires a covariance primitive");
679}

◆ Sexpat() [4/4]

gpr::Sexpat::Sexpat ( std::shared_ptr< const SexpatCF > primitive,
HessianPrecision precision )

Definition at line 681 of file SexpatCF.cpp.

683 : owned_primitive_(std::move(primitive)),
684 primitive_(owned_primitive_.get()),
685 hessian_precision_(precision)
686{
687 if (primitive_ == nullptr)
688 throw std::invalid_argument("Sexpat requires a covariance primitive");
689}

Member Function Documentation

◆ applyJointCrossCovariance()

Eigen::VectorXd gpr::Sexpat::applyJointCrossCovariance ( const Eigen::MatrixXd & left_positions,
const Eigen::MatrixXd & right_positions,
const Eigen::VectorXd & weights ) const
nodiscardoverridevirtual

Contract the joint cross covariance with coefficients in [E; G] order. Operators can apply their feature contractions without a dense tensor.

Reimplemented from gpr::KernelOperator.

Definition at line 1098 of file SexpatOperator.cpp.

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}
virtual Eigen::VectorXd applyJointCrossCovariance(const Eigen::MatrixXd &left_positions, const Eigen::MatrixXd &right_positions, const Eigen::VectorXd &weights) const
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
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.
FieldMatrixd Coord
Definition Macros.h:35

◆ covarianceBlock()

Eigen::MatrixXd gpr::Sexpat::covarianceBlock ( const Eigen::MatrixXd & left_positions,
const Eigen::MatrixXd & right_positions,
Eigen::Index left_channel,
Eigen::Index right_channel ) const
nodiscardoverridevirtual

Covariance between one channel at each set of geometry rows.

Implements gpr::KernelOperator.

Definition at line 701 of file SexpatCF.cpp.

705{
706 return primitive_->inverseDistanceCovarianceBlock(
707 left_positions, right_positions, left_channel, right_channel);
708}

◆ energyDiagonal()

Eigen::VectorXd gpr::Sexpat::energyDiagonal ( const Eigen::MatrixXd & positions) const
nodiscardoverridevirtual

Energy self covariance at each geometry, without an all-pairs matrix.

Reimplemented from gpr::KernelOperator.

Definition at line 691 of file SexpatCF.cpp.

692{
693 if (positions.cols() <= 0 || !positions.allFinite())
694 throw std::invalid_argument(
695 "inverse-distance covariance positions have invalid shape or "
696 "values");
697 return Eigen::VectorXd::Constant(positions.rows(),
698 primitive_->getMagnSigma2());
699}

◆ hessianPrecision()

HessianPrecision gpr::Sexpat::hessianPrecision ( ) const
inlinenodiscardnoexcept

Definition at line 427 of file KernelOperator.h.

428 {
429 return hessian_precision_;
430 }

◆ jointEnergyGradientCrossCovariance()

Eigen::MatrixXd gpr::Sexpat::jointEnergyGradientCrossCovariance ( const Eigen::MatrixXd & left_positions,
const Eigen::MatrixXd & right_positions ) const
nodiscardoverridevirtual

Assemble all Cartesian channels from one sparse pair walk per geometry.

Reimplemented from gpr::KernelOperator.

Definition at line 121 of file SexpatOperator.cpp.

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}
std::vector< CutoffPairFeatures > radialPairFeatures(const Coord &positions, const AtomsConfiguration &configuration)

◆ meanCurvature()

MeanCurvature gpr::Sexpat::meanCurvature ( ) const
inlinenodiscardoverridevirtualnoexcept

Reimplemented from gpr::KernelOperator.

Definition at line 463 of file KernelOperator.h.

◆ meanHessianVector()

bool gpr::Sexpat::meanHessianVector ( const Coord & training,
const Eigen::VectorXd & weights,
const Eigen::VectorXd & position,
const Eigen::VectorXd & direction,
Eigen::VectorXd & action ) const
nodiscardoverridevirtual

Hessian action of the scalar kernel expansion with joint [E; G] training coefficients. False denotes an unsupported derivative.

Reimplemented from gpr::KernelOperator.

Definition at line 178 of file SexpatOperator.cpp.

183{
184 const auto fitted = prepareMeanHessianVector(training, weights);
185 return fitted && fitted(position, direction, action);
186}
MeanHessianFunction prepareMeanHessianVector(const Eigen::MatrixXd &training, const Eigen::VectorXd &weights) const override

◆ predictMeanAlphaK()

void gpr::Sexpat::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.

Definition at line 1131 of file SexpatOperator.cpp.

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}

◆ predictMeanAlphaKPrepared()

void gpr::Sexpat::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.

Definition at line 1338 of file SexpatOperator.cpp.

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}
static void evaluateTogether(const std::vector< const PredictProduct * > &products, std::vector< double > &values)
double evaluateStoredProduct(const double *left, const double *right, int length, ProductMode mode)
ProductMode productMode()
double exp(double x) noexcept
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

◆ prepareAlphaK()

bool gpr::Sexpat::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
nodiscard

Prepare Cartesian derivative weights in active pair coordinates. Uniform translation weights vanish exactly for moving-moving pairs.

Definition at line 1145 of file SexpatOperator.cpp.

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);
1165 prepared.cutoff_rows = radialPairFeatures(
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}
#define EMPTY
Definition Macros.h:39
uint32_t Index_t
Definition Macros.h:17

◆ prepareJointCovarianceTiles()

KernelOperator::JointCovarianceTileFunction gpr::Sexpat::prepareJointCovarianceTiles ( const Eigen::MatrixXd & positions) const
nodiscardoverridevirtual

Own geometry and parameters for repeated single-geometry [E; G] tiles. The arguments index the supplied rows. An empty function requests evaluation through jointEnergyGradientCrossCovariance.

Reimplemented from gpr::KernelOperator.

Definition at line 151 of file SexpatOperator.cpp.

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}

◆ prepareMean()

KernelOperator::MeanFunction gpr::Sexpat::prepareMean ( const Eigen::MatrixXd & training,
const Eigen::VectorXd & weights ) const
nodiscardoverridevirtual

Immutable fitted coefficients with fresh evaluation at every query. An empty function requests the owning generic covariance product.

Reimplemented from gpr::KernelOperator.

Definition at line 1055 of file SexpatOperator.cpp.

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}

◆ prepareMeanHessian()

KernelOperator::MeanHessianPreparation gpr::Sexpat::prepareMeanHessian ( const Eigen::MatrixXd & training,
const Eigen::VectorXd & weights ) const
nodiscardoverridevirtual

Own the fitted mean coefficients and construct a scoped linear Hessian operator at each requested geometry. No query is retained by the fitted model. An empty preparation requests the directional path.

Reimplemented from gpr::KernelOperator.

Definition at line 1011 of file SexpatOperator.cpp.

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}
std::function< bool(const Eigen::VectorXd &, Eigen::VectorXd &)> HessianAction
std::function< HessianAction(const Eigen::VectorXd &)> MeanHessianPreparation
@ LongDouble
Extended-precision (long double) per-query setup.

◆ prepareMeanHessianMatrix()

Sexpat::MeanHessianMatrixFunction gpr::Sexpat::prepareMeanHessianMatrix ( const Eigen::MatrixXd & training,
const Eigen::VectorXd & weights ) const
nodiscard

Dense Sexpat mean Hessian from two GEMMs and the pair blocks.

Definition at line 975 of file SexpatOperator.cpp.

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}
std::function< bool(const Eigen::VectorXd &, Eigen::MatrixXd &)> MeanHessianMatrixFunction

◆ prepareMeanHessianVector()

KernelOperator::MeanHessianFunction gpr::Sexpat::prepareMeanHessianVector ( const Eigen::MatrixXd & training,
const Eigen::VectorXd & weights ) const
nodiscardoverridevirtual

Owning fitted derivative coefficients; query geometry is evaluated afresh. An empty function requests the generic scalar-kernel action.

Reimplemented from gpr::KernelOperator.

Definition at line 188 of file SexpatOperator.cpp.

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}
MeanHessianPreparation prepareMeanHessian(const Eigen::MatrixXd &training, const Eigen::VectorXd &weights) const override

◆ setHessianPrecision()

void gpr::Sexpat::setHessianPrecision ( HessianPrecision precision)
inlinenoexcept

Definition at line 423 of file KernelOperator.h.

424 {
425 hessian_precision_ = precision;
426 }

◆ setUseLongDoubleHessian()

void gpr::Sexpat::setUseLongDoubleHessian ( bool enabled)
inlinenoexcept

Definition at line 431 of file KernelOperator.h.

432 {
433 hessian_precision_ =
435 }

◆ trainingGradientAlphaK()

void gpr::Sexpat::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

Add alpha^T (dK/dtheta) alpha for log amplitude and log lengths. Local evaluation enters no MPI collectives. Distributed evaluation assigns each symmetric training pair to one rank and reduces once.

Definition at line 1599 of file SexpatOperator.cpp.

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
1617 using Sum = linalg::CompensatedSum;
1618 Eigen::Index rank = 0, ranks = 1;
1619 linalg::MpiContext selected = linalg::MpiContext::local();
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
1675 .cutoff_gradient_weights[i][a -
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}
static DistributedState & instance()
void exact_sum_bcast(ExactSum *sums, int count, const MpiContext &context)
static MpiContext local() noexcept
Definition MpiContext.h:75

◆ useLongDoubleHessian()

bool gpr::Sexpat::useLongDoubleHessian ( ) const
inlinenodiscardnoexcept

Definition at line 436 of file KernelOperator.h.

437 {
438 return hessian_precision_ == HessianPrecision::LongDouble;
439 }

The documentation for this class was generated from the following files: