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

Pair-type inverse-distance squared-exponential primitive. More...

#include <gpr/covariance_functions/SexpatCF.h>

Classes

struct  CrossBlockGeometry
struct  PriorState
 Every prior the kernel places on its magnitude and length scales. More...

Public Types

using AlphaKPairInfo = Sexpat::AlphaKPairInfo
using PreparedAlphaK = Sexpat::PreparedAlphaK
using HessianPrecision = Sexpat::HessianPrecision
using ExpDistArray
 Calculates covariances between the derivatives.
using SharedDerivatives = Derivatives<std::vector<FieldMatrixd>>
 Evaluate gradient of covariance function with respect to both input variables x1 and x2 (in different dimensions).

Public Member Functions

 SexpatCF ()
virtual ~SexpatCF ()
void setHessianPrecision (HessianPrecision precision) noexcept
HessianPrecision hessianPrecision () const noexcept
void setUseLongDoubleHessian (bool enabled) noexcept
bool useLongDoubleHessian () const noexcept
bool meanHessianVector (const Coord &training, const Eigen::VectorXd &weights, const Eigen::VectorXd &position, const Eigen::VectorXd &direction, Eigen::VectorXd &action) const
double calculateLogPrior ()
 Evaluate the log prior density of the parameters.
FieldMatrixd calculateLogPriorGradient ()
 Evaluate the gradient of the log prior density of the parameters with respect to parameters.
void calculateCovarianceMatrix (const Coord &x1, Coord &x2, FieldMatrixd &C)
 Evaluate covariance matrix between two input vectors.
void correlationDistances (const Coord &left, const Coord &right, const AtomsConfiguration &configuration, FieldMatrixd &distances) const
void calculateTrainingCovarianceMatrix (const Coord &x, FieldMatrixd &C)
 Evaluate the prior variance for each training input.
void calculateGradOfCovMatrix (const Coord &x1, Coord &x2, std::vector< FieldMatrixd > &DKff)
 Evaluate gradient of covariance function with respect to the parameters.
void calculateGradOfCovMatrixWithDerivatives (const Coord &x1, Coord &x2, FieldMatrixIdx &dims, std::vector< FieldMatrixd > &DKff)
 Evaluate gradient of covariance function, of which has been taken partial derivative with respect to x1, with respect to parameters.
void calculateGradOfCovMatrixWithDerivatives2 (const Coord &x1, Coord &x2, FieldMatrixIdx &dims1, FieldMatrixIdx &dims2, std::vector< FieldMatrixd > &DKff)
 Evaluate gradient of covariance function, of which has been taken partial derivatives with respect to both input variables x1 and x2 with respect to parameters.
void calculateDirectionalCovarianceMatrix (const Coord &x1, Coord &x2, const Eigen::VectorXd &direction, FieldMatrixd &first, FieldMatrixd &second)
 Evaluate the directional first and second derivatives of the covariance matrix along a parameter-space direction.
void calculateDirectionalCovarianceMatrixWithDerivatives (const Coord &x1, Coord &x2, FieldMatrixIdx &dims, const Eigen::VectorXd &direction, FieldMatrixd &first, FieldMatrixd &second)
 Evaluate directional first and second derivatives of the derivative-vs-value covariance block.
void calculateDirectionalCovarianceMatrixWithDerivatives2 (const Coord &x1, Coord &x2, FieldMatrixIdx &dims1, FieldMatrixIdx &dims2, const Eigen::VectorXd &direction, FieldMatrixd &first, FieldMatrixd &second)
 Evaluate directional first and second derivatives of the derivative-vs-derivative covariance block.
bool buildCrossBlockGeometry (const Coord &x1, const Coord &x2, uint8_t derivative_options, const FieldMatrixIdx &dims1, const FieldMatrixIdx &dims2, CrossBlockGeometry &geometry) const
 Build theta-independent pairtype geometry for a covariance block.
bool buildCrossBlockDerivativesOnly (const Coord &x1, const Coord &x2, uint8_t derivative_options, const FieldMatrixIdx &dims1, const FieldMatrixIdx &dims2, CrossBlockGeometry &geometry) const
 Populate only the derivative fields (d1, d2, d12) of a CrossBlockGeometry, skipping the per-pairtype distance computation.
bool buildSharedDistanceForTrainingGeometry (const Coord &x_loc, std::vector< FieldMatrixd > &shared_distance_neg_per_pt) const
 Build the per-pairtype distance tensor at unit lengthscale for a single coordinate slice (shared across all training-cov blocks). The output convention matches CrossBlockGeometry.distance: shared_distance_neg_per_pt[pt] = -dist_at_vec(x_loc, x_loc, unit)[pt].
bool evaluateCrossBlockGeometry (const CrossBlockGeometry &geometry, const Eigen::VectorXd &theta, FieldMatrixd &out) const
 Evaluate a cross-block geometry at packed Sexpat log parameters.
bool evaluateCrossBlockGeometryShared (const CrossBlockGeometry &geometry, const std::vector< FieldMatrixd > &shared_distance_neg_per_pt, const Eigen::VectorXd &theta, FieldMatrixd &out) const
 Same as evaluateCrossBlockGeometry but reads the per-pairtype distance from an externally-shared tensor (negated, matching the sign convention of buildCrossBlockGeometry). The supplied geometry's .distance field is ignored; .d1, .d2, .d12 are still consulted.
bool buildSharedKernel (const std::vector< FieldMatrixd > &shared_distance_neg_per_pt, const Eigen::VectorXd &theta, FieldMatrixd &kernel_out) const
 Apply theta to a shared distance to produce the kernel value K(theta)[n, m] = exp(theta(0)) * exp(-0.5 * sum_pt exp(-2 theta(1+pt)).
bool evaluateCrossBlockGeometryWithSharedKernel (const CrossBlockGeometry &geometry, const FieldMatrixd &shared_kernel, const Eigen::VectorXd &theta, FieldMatrixd &out) const
 Evaluate a derivative-only block against a pre-computed shared kernel matrix (from buildSharedKernel). No exp() per call.
bool calculateDirectionalCovarianceMatrixFromGeometry (const FieldMatrixd &shared_kernel, const std::vector< FieldMatrixd > &shared_distance_neg_per_pt, const Eigen::VectorXd &theta, const Eigen::VectorXd &direction, FieldMatrixd &first, FieldMatrixd &second) const
 Directional first and second derivatives for the Kff block from shared training geometry.
bool calculateDirectionalCovarianceMatrixWithDerivativesFromGeometry (const CrossBlockGeometry &geometry, const FieldMatrixd &shared_kernel, const std::vector< FieldMatrixd > &shared_distance_neg_per_pt, const Eigen::VectorXd &theta, const Eigen::VectorXd &direction, FieldMatrixd &first, FieldMatrixd &second) const
 Directional first and second derivatives for a Kdf block from shared training geometry.
bool calculateDirectionalCovarianceMatrixWithDerivatives2FromGeometry (const CrossBlockGeometry &geometry, const FieldMatrixd &shared_kernel, const std::vector< FieldMatrixd > &shared_distance_neg_per_pt, const Eigen::VectorXd &theta, const Eigen::VectorXd &direction, FieldMatrixd &first, FieldMatrixd &second) const
 Directional first and second derivatives for a D/Kdf2 block from shared training geometry.
bool calculateGradOfCovMatrixFromGeometry (const FieldMatrixd &shared_kernel, const std::vector< FieldMatrixd > &shared_distance_neg_per_pt, const Eigen::VectorXd &theta, std::vector< FieldMatrixd > &DKff, const std::vector< Eigen::Index > *parameter_indices=nullptr) const
 Geometry-path replacement for calculateGradOfCovMatrix. Produces DKff[0] = K (untruncated kernel), DKff[1+pt] = K * inv_l_pt^2 * shared_distance_neg[pt] (== -K * dist_pt_actual in the legacy negated sign convention). Scalar-length case collapses to a single DKff[1] entry that sums across pairtypes. An optional nonempty parameter list selects output blocks in the given order. All parameters still contribute to the kernel and its Cartesian derivatives; only the requested hyperparameter derivatives are formed.
bool calculateGradOfCovMatrixWithDerivativesFromGeometry (const CrossBlockGeometry &geometry, const FieldMatrixd &shared_kernel, const std::vector< FieldMatrixd > &shared_distance_neg_per_pt, const Eigen::VectorXd &theta, std::vector< FieldMatrixd > &DKff, const std::vector< Eigen::Index > *parameter_indices=nullptr) const
 Geometry-path replacement for calculateGradOfCovMatrixWithDerivatives (Kdf block dK).
bool calculateGradOfCovMatrixWithDerivatives2FromGeometry (const CrossBlockGeometry &geometry, const FieldMatrixd &shared_kernel, const std::vector< FieldMatrixd > &shared_distance_neg_per_pt, const Eigen::VectorXd &theta, std::vector< FieldMatrixd > &DKff, const std::vector< Eigen::Index > *parameter_indices=nullptr) const
 Geometry-path replacement for calculateGradOfCovMatrixWithDerivatives2 (D and Kdf2 blocks).
bool applyCrossBlockGeometryToVector (const CrossBlockGeometry &geometry, const Eigen::VectorXd &theta, const Eigen::VectorXd &weights, bool transpose_field, Eigen::VectorXd &out) const
 Apply a cross-block geometry directly to a vector.
void ginput2 (const Coord &x1, Coord &x2, FieldMatrixIdx &dims, std::vector< FieldMatrixd > &DKff, ExpDistArray *out_expdist=nullptr)
void ginput3 (const Coord &x1, Coord &x2, FieldMatrixIdx &dims1, FieldMatrixIdx &dims2, std::vector< FieldMatrixd > &DKff, ExpDistArray *out_expdist=nullptr, const SharedDerivatives *precomputed=nullptr)
void ginput4 (const Coord &x1, Coord &x2, FieldMatrixIdx &dims, std::vector< FieldMatrixd > &DKff, ExpDistArray *out_expdist=nullptr)
 Evaluate gradient of covariance function with respect to x.
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)
 Per-test-point predict mean (energy + gradient) via the Schmitz/Chmiela JPCL 2022 eq.6 alpha-K early contraction applied at the per-pair level.
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
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)
void setMagnSigma2 (double value)
void setLengthScale (double value)
void setFarFieldRadius (double radius)
double farFieldRadius () const
void setManifoldChart (std::shared_ptr< const geometry::InternalCoordinateChart > chart, double length_scale)
void clearManifoldChart ()
bool usesManifoldChart () const noexcept
const std::shared_ptr< const geometry::InternalCoordinateChart > & manifoldChart () const noexcept
Eigen::Index manifoldDimensions () const noexcept
FieldMatrixd manifoldJointEnergyGradientCovariance (const Coord &positions) const
FieldMatrixd manifoldJointEnergyGradientCrossCovariance (const Coord &left_positions, const Coord &right_positions) const
void resetManifoldGeometryRowsEvaluatedForTesting () const noexcept
void addManifoldGeometryRowsEvaluatedForTesting (Eigen::Index left_rows, Eigen::Index right_rows) const noexcept
std::size_t manifoldGeometryRowsEvaluatedForTesting () const noexcept
void setGeodesicHeatReferencePath (const Coord &reference_path, double covariance_weight)
void setGeodesicHeatKernel (std::shared_ptr< const GeodesicHeatEnergyForceKernel > kernel)
 Attach an immutable heat component with its own reference and metric.
const std::shared_ptr< const GeodesicHeatEnergyForceKernel > & geodesicHeatKernel () const noexcept
void rescaleGeodesicHeatCovariance (double factor)
 Convert the additive component to a different output variance unit.
void clearGeodesicHeatKernel () noexcept
bool usesGeodesicHeatKernel () const noexcept
Eigen::Index geodesicHeatDimensions () const noexcept
FieldMatrixd geodesicHeatJointEnergyGradientCovariance (const Coord &positions) const
FieldMatrixd geodesicHeatJointEnergyGradientCrossCovariance (const Coord &left_positions, const Coord &right_positions) const
void setConfInfo (const AtomsConfiguration &value)
const AtomsConfiguration & getConfInfo () const noexcept
void setParameters (const Eigen::VectorXd &w)
 Set parameters of this covariance function using the provided vector.
double getMagnSigma2 ()
double getMagnSigma2 () const
FieldMatrixd & getLengthScaleRef ()
const FieldMatrixd & getLengthScaleRef () const
FieldMatrixd & getAtomisticLengthScaleRef () noexcept
 Pair-type metric retained independently of the chart's fitted length.
const FieldMatrixd & getAtomisticLengthScaleRef () const noexcept
std::shared_ptr< const KernelOperator > assembledOperator () const
 The configured base and optional additive heat component.
void clear ()
void setPriorParametersGaussian (const PriorBase &prior)
void setPriorParametersSqrtt (const PriorBase &prior)
void setPriorParametersLogNormal (const PriorBase &prior)
PriorBase getPriorParametersGaussian ()
PriorBase getPriorParametersSqrtt ()
PriorBase getPriorParametersLogNormal ()
void setUseLogNormalMagnPrior (bool enabled) noexcept
bool useLogNormalMagnPrior () const noexcept
void setModelProfile (GPModelProfile profile)
GPModelProfile getModelProfile () const noexcept
void setLengthScalePriorWeights (const Eigen::VectorXd &weights)
const Eigen::VectorXd & lengthScalePriorWeights () const noexcept
void setHierarchicalPrior (const Eigen::VectorXd &mu_log, double s2_log)
void setHierarchicalPrior (const Eigen::VectorXd &mu_log, double s2_log, const Eigen::VectorXd &s2_log_per)
const Eigen::VectorXd & hierarchicalPriorMu () const noexcept
void setHierarchicalAnchorMask (std::vector< char > mask)
bool hierarchicalAnchored (Eigen::Index n) const noexcept
double hierarchicalPriorVariance (Eigen::Index n) const noexcept
 Variance of packed parameter ~n~ under the hierarchical prior.
void clearHierarchicalPrior ()
void setPcLengthScalePrior (const Eigen::VectorXd &lambda)
void clearPcLengthScalePrior ()
bool hasHierarchicalPrior () const
bool hasPcLengthScalePrior () const noexcept
PriorState priorState () const
void restorePriorState (PriorState state)
Eigen::VectorXd combineParameters ()
 Combine parameters of the covariance function into one Eigen vector.
double calculateDirectionalLogPriorCurvature (const Eigen::VectorXd &direction) const
 Evaluate the second directional derivative of log p(theta) along the packed log-parameter direction.
void cacheDistances (const Coord &x1, const Coord &x2)
 Pre-compute and cache inverse distances for the given positions.
void clearDistanceCache ()
 Invalidate the distance cache.
bool hasDistanceCache () const

Friends

class Sexpat

Detailed Description

Pair-type inverse-distance squared-exponential primitive.

Geodesic add is assembled as Sum(Sexpat, GeodesicHeat). Manifold dispatch is assembled as Pullback(SE, chart). A geodesic summand can augment either base; chart and pair-metric length scales are independent.

Definition at line 74 of file SexpatCF.h.

Member Typedef Documentation

◆ AlphaKPairInfo

◆ ExpDistArray

Initial value:
Eigen::Array<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>

Calculates covariances between the derivatives.

Parameters
x1Matrix of coordinates
x2Matrix of coordinates
dimsCoordinate-dimension indices for the derivative covariance.
DKffOutput derivative-covariance blocks.
out_expdistOptional output array of the shared exponential distance factors. Row-major array of exp(-0.5 * d^2), the shared squared-exponential factor. ginput2 and ginput3 both build one; the out-parameter below hands it to a caller that would otherwise recompute the same transcendental over the same distances.

Definition at line 472 of file SexpatCF.h.

◆ HessianPrecision

◆ PreparedAlphaK

◆ SharedDerivatives

Evaluate gradient of covariance function with respect to both input variables x1 and x2 (in different dimensions).

This function takes a covariance function structure GPCF, a matrix X of input vectors and returns DKff, the gradients of twice derivatived covariance matrix K(df,df) = dk(X1,X2)/dX1dX2 (cell array with matrix elements). The derivative is calculated in multidimensional problem between input's observation dimensions which are not same. This subfunction is needed when using derivative observations.

Parameters
x1Configurations supplying the first covariance argument.
x2Configurations supplying the second covariance argument.
dims1Coordinate-dimension indices differentiated in x1.
dims2Coordinate-dimension indices differentiated in x2.
DKffOutput second-derivative covariance blocks. Optional precomputed D1/D2/D12 for ginput3. Its caller calculateGradOfCovMatrixWithDerivatives2 asks calculateDerivativesDiffDim for a superset of the same fields over the same inputs, and the direction argument that appears to distinguish the two calls is unread (Gradient.cpp), so the shared part is identical. Passing it in lets the pair be computed once.

Definition at line 502 of file SexpatCF.h.

Constructor & Destructor Documentation

◆ SexpatCF()

gpr::SexpatCF::SexpatCF ( )

Definition at line 245 of file SexpatCF.cpp.

246{
247 clear();
248}

◆ ~SexpatCF()

gpr::SexpatCF::~SexpatCF ( )
virtual

Definition at line 250 of file SexpatCF.cpp.

251{
252 clear();
253}

Member Function Documentation

◆ addManifoldGeometryRowsEvaluatedForTesting()

void gpr::SexpatCF::addManifoldGeometryRowsEvaluatedForTesting ( Eigen::Index left_rows,
Eigen::Index right_rows ) const
inlinenoexcept

Definition at line 638 of file SexpatCF.h.

640 {
641 noteManifoldGeometryRows(left_rows, right_rows);
642 }

◆ applyCrossBlockGeometryToVector()

bool gpr::SexpatCF::applyCrossBlockGeometryToVector ( const CrossBlockGeometry & geometry,
const Eigen::VectorXd & theta,
const Eigen::VectorXd & weights,
bool transpose_field,
Eigen::VectorXd & out ) const
nodiscard

Apply a cross-block geometry directly to a vector.

When transpose_field is false, computes out = A(theta)^T * weights. When it is true, computes out = A(theta) * weights.

Definition at line 2003 of file SexpatCF.cpp.

2007{
2008 out.resize(0);
2009 if (!geometry.valid || geometry.distance.empty() || theta.size() < 2) {
2010 return false;
2011 }
2012
2013 const auto n_pairtypes =
2014 static_cast<Eigen::Index>(geometry.distance.size());
2015 const auto n_length_scales = lengthScale.size();
2016 if (n_length_scales <= 0 || theta.size() < 1 + n_length_scales) {
2017 return false;
2018 }
2019 const bool scalar_length = n_length_scales == 1;
2020 if (!scalar_length && n_length_scales != n_pairtypes) {
2021 return false;
2022 }
2023
2024 const Eigen::Index rows = geometry.distance[0].rows();
2025 const Eigen::Index cols = geometry.distance[0].cols();
2026 if (rows <= 0 || cols <= 0) return false;
2027
2028 const Eigen::Index expected_weights = transpose_field ? cols : rows;
2029 const Eigen::Index expected_out = transpose_field ? rows : cols;
2030 if (weights.size() != expected_weights) return false;
2031
2032 const bool need_d1 =
2033 geometry.derivative_options == OptionsForGradCalculation::D1 ||
2034 geometry.derivative_options ==
2037 const bool need_d2 =
2038 geometry.derivative_options ==
2041 if (!need_d1 && geometry.derivative_options != 0) return false;
2042 if (need_d1 && geometry.d1.empty()) return false;
2043 if (need_d2 && (geometry.d2.empty() || geometry.d12.empty())) return false;
2044
2045 std::vector<double> inv_length_sq(static_cast<std::size_t>(n_pairtypes),
2046 0.0);
2047 for (Eigen::Index pt = 0; pt < n_pairtypes; ++pt) {
2048 const double log_length = scalar_length ? theta(1) : theta(1 + pt);
2049 inv_length_sq[static_cast<std::size_t>(pt)] =
2050 numerics::exp(-2.0 * log_length);
2051 }
2052
2053 out.resize(expected_out);
2054 out.setZero();
2055 const double magn_sigma = numerics::exp(theta(0));
2056
2057 auto add_entry = [&](Eigen::Index row, Eigen::Index col, double value) {
2058 if (transpose_field) {
2059 out(row) += value * weights(col);
2060 } else {
2061 out(col) += value * weights(row);
2062 }
2063 };
2064
2065 for (Eigen::Index row = 0; row < rows; ++row) {
2066 for (Eigen::Index col = 0; col < cols; ++col) {
2067 double q = 0.0;
2068 double d1 = 0.0;
2069 double d2 = 0.0;
2070 double d12 = 0.0;
2071 for (Eigen::Index pt = 0; pt < n_pairtypes; ++pt) {
2072 const double coeff =
2073 inv_length_sq[static_cast<std::size_t>(pt)];
2074 const auto& dist =
2075 geometry.distance[static_cast<std::size_t>(pt)];
2076 q += coeff * dist(row, col);
2077 if (need_d1) {
2078 d1 += coeff *
2079 geometry.d1[static_cast<std::size_t>(pt)](row, col);
2080 }
2081 if (need_d2) {
2082 d2 += coeff *
2083 geometry.d2[static_cast<std::size_t>(pt)](row, col);
2084 d12 += coeff *
2085 geometry.d12[static_cast<std::size_t>(pt)](row, col);
2086 }
2087 }
2088
2089 double value = magn_sigma * numerics::exp(-0.5 * q);
2090 switch (geometry.derivative_options) {
2091 case 0:
2092 break;
2094 value *= -0.5 * d1;
2095 break;
2099 value *= (-0.5 * d12 + 0.25 * d1 * d2);
2100 break;
2101 default:
2102 return false;
2103 }
2104 add_entry(row, col, value);
2105 }
2106 }
2107 return true;
2108}
@ D1
Definition Enums.h:19
@ D12
Definition Enums.h:21
@ D2
Definition Enums.h:20
eon_relax_band_t eon_relax_surface_fn void eon_relax_outcome_t * out
double exp(double x) noexcept

◆ assembledOperator()

std::shared_ptr< const KernelOperator > gpr::SexpatCF::assembledOperator ( ) const
nodiscard

The configured base and optional additive heat component.

Definition at line 585 of file SexpatCF.cpp.

586{
587 if (!usesManifoldChart() && !usesGeodesicHeatKernel()) return nullptr;
588 std::shared_ptr<const KernelOperator> base;
589 if (usesManifoldChart()) {
590 if (chart_length_scale_.size() != 1) {
591 throw std::logic_error(
592 "chart covariance requires one intrinsic length scale");
593 }
594 base = std::make_shared<Pullback>(manifold_chart_, magnSigma2,
595 chart_length_scale_(0, 0));
596 } else {
597 auto primitive = std::make_shared<SexpatCF>(*this);
598 primitive->clearDistanceCache();
599 base = std::make_shared<Sexpat>(
600 std::shared_ptr<const SexpatCF>(std::move(primitive)));
601 }
602 if (!usesGeodesicHeatKernel()) return base;
603 return std::make_shared<Sum>(
604 std::vector<std::shared_ptr<const KernelOperator>>{
605 std::move(base),
606 std::make_shared<GeodesicHeat>(geodesic_heat_kernel_)});
607}
bool usesManifoldChart() const noexcept
Definition SexpatCF.h:616
bool usesGeodesicHeatKernel() const noexcept
Definition SexpatCF.h:664

◆ buildCrossBlockDerivativesOnly()

bool gpr::SexpatCF::buildCrossBlockDerivativesOnly ( const Coord & x1,
const Coord & x2,
uint8_t derivative_options,
const FieldMatrixIdx & dims1,
const FieldMatrixIdx & dims2,
CrossBlockGeometry & geometry ) const
nodiscard

Populate only the derivative fields (d1, d2, d12) of a CrossBlockGeometry, skipping the per-pairtype distance computation.

Companion to buildCrossBlockGeometry for callers that already hold a shared per-pairtype distance tensor across many blocks with identical atom positions (e.g. the SCG training-cov assembly, where each (block_n, block_m) (D+1)*N row slice contains the same coordinates with different derivative-dim tags by construction of assembleMatrixOfRepetitiveCoordinates). The shared distance must be applied at evaluate time via evaluateCrossBlockGeometryShared.

Definition at line 931 of file SexpatCF.cpp.

935{
936 if (usesManifoldChart() || usesGeodesicHeatKernel()) return false;
937 geometry = CrossBlockGeometry{};
938 geometry.derivative_options = derivative_options;
939
940 if (conf_info.n_pt <= 0 || x1.rows() <= 0 || x2.rows() <= 0) {
941 return false;
942 }
943 const uint8_t supported_options = OptionsForGradCalculation::D1 |
946 if ((derivative_options & ~supported_options) != 0) return false;
947 if (derivative_options != 0 &&
948 derivative_options != OptionsForGradCalculation::D1 &&
949 derivative_options != supported_options) {
950 return false;
951 }
952
953 // .distance field intentionally left empty -- caller provides it via
954 // evaluateCrossBlockGeometryShared / WithSharedKernel.
955 if (derivative_options == 0) {
956 geometry.valid = true;
957 return true;
958 }
959
960 FieldMatrixd unit_length_scale(1, conf_info.n_pt);
961 unit_length_scale.setOnes();
962
963 auto copy_pairtype_fields = [&](const std::vector<FieldMatrixd>& source,
964 std::vector<FieldMatrixd>& target) -> bool {
965 if (source.size() != static_cast<std::size_t>(conf_info.n_pt)) {
966 return false;
967 }
968 target.resize(source.size());
969 for (std::size_t pt = 0; pt < source.size(); ++pt) {
970 target[pt] = -source[pt];
971 }
972 return true;
973 };
974
975 aux::Gradient grad_calculator;
976 grad_calculator.setFarFieldRadius(far_field_radius_);
977 Derivatives<std::vector<FieldMatrixd>> derivatives;
978 Derivatives<std::vector<FieldMatrixd>> derivatives_pt;
979
980 if (derivative_options == OptionsForGradCalculation::D1) {
981 const uint8_t calc_options =
983 grad_calculator.calculateDerivativesSameDim(
984 x1, x2, conf_info, unit_length_scale, dims1, calc_options,
985 derivatives, derivatives_pt);
986 if (!copy_pairtype_fields(derivatives_pt.D1, geometry.d1)) {
987 return false;
988 }
989 geometry.valid = true;
990 return true;
991 }
992
993 const uint8_t calc_options =
997 const bool same_dimension =
998 dims1.size() == dims2.size() && (dims1.array() == dims2.array()).all();
999 if (same_dimension) {
1000 grad_calculator.calculateDerivativesSameDim(
1001 x1, x2, conf_info, unit_length_scale, dims1, calc_options,
1002 derivatives, derivatives_pt);
1003 } else {
1004 grad_calculator.calculateDerivativesDiffDim(
1005 x1, x2, conf_info, unit_length_scale, dims1, dims2, calc_options,
1006 Directions::y, derivatives, derivatives_pt);
1007 }
1008
1009 if (!copy_pairtype_fields(derivatives_pt.D1, geometry.d1) ||
1010 !copy_pairtype_fields(derivatives_pt.D2, geometry.d2) ||
1011 !copy_pairtype_fields(derivatives_pt.D12, geometry.d12)) {
1012 return false;
1013 }
1014 geometry.valid = true;
1015 return true;
1016}
@ y
Definition Enums.h:28
@ D1_pt
Definition Enums.h:23
@ D2_pt
Definition Enums.h:24
@ D12_pt
Definition Enums.h:25
void setFarFieldRadius(double radius)
Definition Gradient.cpp:885
void calculateDerivativesDiffDim(const gpr::Coord &x1, const gpr::Coord &x2, const gpr::AtomsConfiguration &conf_info, const gpr::FieldMatrixd &lengthScale, const gpr::FieldMatrixIdx &dims1, const gpr::FieldMatrixIdx &dims2, const uint8_t calc_options, const uint8_t direction_x2, gpr::Derivatives< std::vector< gpr::FieldMatrixd > > &derivatives, gpr::Derivatives< std::vector< gpr::FieldMatrixd > > &derivatives_pt)
Evaluate gradient of covariance function, of which has been taken partial derivatives with respect to...
Definition Gradient.cpp:655
void calculateDerivativesSameDim(const gpr::Coord &x1, const gpr::Coord &x2, const gpr::AtomsConfiguration &conf_info, const gpr::FieldMatrixd &lengthScale, const gpr::FieldMatrixIdx &dims, uint8_t calc_options, gpr::Derivatives< std::vector< gpr::FieldMatrixd > > &derivatives, gpr::Derivatives< std::vector< gpr::FieldMatrixd > > &derivatives_pt)
Evaluate gradient of covariance function with respect to both input variables x and x2 (in same dimen...
Definition Gradient.cpp:555
Eigen::Matrix< double, EigenDynamic, EigenDynamic, FieldMatrixStorage > FieldMatrixd
Definition Macros.h:25

◆ buildCrossBlockGeometry()

bool gpr::SexpatCF::buildCrossBlockGeometry ( const Coord & x1,
const Coord & x2,
uint8_t derivative_options,
const FieldMatrixIdx & dims1,
const FieldMatrixIdx & dims2,
CrossBlockGeometry & geometry ) const
nodiscard

Build theta-independent pairtype geometry for a covariance block.

The stored fields are raw pairtype contributions. They can be evaluated at any packed Sexpat log-parameter vector without re-walking atomic coordinates.

Definition at line 806 of file SexpatCF.cpp.

811{
812 if (usesManifoldChart() || usesGeodesicHeatKernel()) return false;
813 geometry = CrossBlockGeometry{};
814 geometry.derivative_options = derivative_options;
815
816 if (conf_info.n_pt <= 0 || x1.rows() <= 0 || x2.rows() <= 0) {
817 return false;
818 }
819 const uint8_t supported_options = OptionsForGradCalculation::D1 |
822 if ((derivative_options & ~supported_options) != 0) return false;
823 if (derivative_options != 0 &&
824 derivative_options != OptionsForGradCalculation::D1 &&
825 derivative_options != supported_options) {
826 return false;
827 }
828
829 FieldMatrixd unit_length_scale(1, conf_info.n_pt);
830 unit_length_scale.setOnes();
831
832 aux::Distance distance;
833 distance.setFarFieldRadius(far_field_radius_);
834 std::vector<FieldMatrixd> distance_pt;
835 distance.dist_at_vec(x1, x2, conf_info, unit_length_scale, distance_pt);
836 if (distance_pt.size() != static_cast<std::size_t>(conf_info.n_pt)) {
837 return false;
838 }
839
840 geometry.distance.resize(distance_pt.size());
841 for (std::size_t pt = 0; pt < distance_pt.size(); ++pt) {
842 geometry.distance[pt] = -distance_pt[pt];
843 }
844
845 auto copy_pairtype_fields = [&](const std::vector<FieldMatrixd>& source,
846 std::vector<FieldMatrixd>& target) -> bool {
847 if (source.size() != static_cast<std::size_t>(conf_info.n_pt)) {
848 return false;
849 }
850 target.resize(source.size());
851 for (std::size_t pt = 0; pt < source.size(); ++pt) {
852 target[pt] = -source[pt];
853 }
854 return true;
855 };
856
857 if (derivative_options == 0) {
858 geometry.valid = true;
859 return true;
860 }
861
862 aux::Gradient grad_calculator;
863 grad_calculator.setFarFieldRadius(far_field_radius_);
864 Derivatives<std::vector<FieldMatrixd>> derivatives;
865 Derivatives<std::vector<FieldMatrixd>> derivatives_pt;
866
867 if (derivative_options == OptionsForGradCalculation::D1) {
868 const uint8_t calc_options =
870 grad_calculator.calculateDerivativesSameDim(
871 x1, x2, conf_info, unit_length_scale, dims1, calc_options,
872 derivatives, derivatives_pt);
873 if (!copy_pairtype_fields(derivatives_pt.D1, geometry.d1)) {
874 return false;
875 }
876 geometry.valid = true;
877 return true;
878 }
879
880 const uint8_t calc_options =
884
885 const bool same_dimension =
886 dims1.size() == dims2.size() && (dims1.array() == dims2.array()).all();
887 if (same_dimension) {
888 grad_calculator.calculateDerivativesSameDim(
889 x1, x2, conf_info, unit_length_scale, dims1, calc_options,
890 derivatives, derivatives_pt);
891 } else {
892 grad_calculator.calculateDerivativesDiffDim(
893 x1, x2, conf_info, unit_length_scale, dims1, dims2, calc_options,
894 Directions::y, derivatives, derivatives_pt);
895 }
896
897 if (!copy_pairtype_fields(derivatives_pt.D1, geometry.d1) ||
898 !copy_pairtype_fields(derivatives_pt.D2, geometry.d2) ||
899 !copy_pairtype_fields(derivatives_pt.D12, geometry.d12)) {
900 return false;
901 }
902
903 geometry.valid = true;
904 return true;
905}
void dist_at_vec(const gpr::Coord &x1, const gpr::Coord &x2, const gpr::AtomsConfiguration &conf_info, const gpr::FieldMatrixd &lengthscale, std::vector< gpr::FieldMatrixd > &dist)
Similar to dist_at but calculates vector of distances for every pair of moving and frozen atoms.
Definition Distance.cpp:796
void setFarFieldRadius(double radius)
Definition Distance.cpp:299

◆ buildSharedDistanceForTrainingGeometry()

bool gpr::SexpatCF::buildSharedDistanceForTrainingGeometry ( const Coord & x_loc,
std::vector< FieldMatrixd > & shared_distance_neg_per_pt ) const
nodiscard

Build the per-pairtype distance tensor at unit lengthscale for a single coordinate slice (shared across all training-cov blocks). The output convention matches CrossBlockGeometry.distance: shared_distance_neg_per_pt[pt] = -dist_at_vec(x_loc, x_loc, unit)[pt].

Definition at line 907 of file SexpatCF.cpp.

910{
911 if (usesManifoldChart() || usesGeodesicHeatKernel()) return false;
912 shared_distance_neg_per_pt.clear();
913 if (conf_info.n_pt <= 0 || x_loc.rows() <= 0) return false;
914 FieldMatrixd unit_length_scale(1, conf_info.n_pt);
915 unit_length_scale.setOnes();
916 aux::Distance distance;
917 distance.setFarFieldRadius(far_field_radius_);
918 std::vector<FieldMatrixd> distance_pt;
919 distance.dist_at_vec(x_loc, x_loc, conf_info, unit_length_scale,
920 distance_pt);
921 if (distance_pt.size() != static_cast<std::size_t>(conf_info.n_pt)) {
922 return false;
923 }
924 shared_distance_neg_per_pt.resize(distance_pt.size());
925 for (std::size_t pt = 0; pt < distance_pt.size(); ++pt) {
926 shared_distance_neg_per_pt[pt] = -distance_pt[pt];
927 }
928 return true;
929}

◆ buildSharedKernel()

bool gpr::SexpatCF::buildSharedKernel ( const std::vector< FieldMatrixd > & shared_distance_neg_per_pt,
const Eigen::VectorXd & theta,
FieldMatrixd & kernel_out ) const
nodiscard

Apply theta to a shared distance to produce the kernel value K(theta)[n, m] = exp(theta(0)) * exp(-0.5 * sum_pt exp(-2 theta(1+pt)).

  • (-shared_distance_neg[pt][n, m])). Pre-computed once per inner iter and reused by per-block apply.

Definition at line 1309 of file SexpatCF.cpp.

1312{
1313 auto fail = [&kernel_out]() {
1314 kernel_out.resize(0, 0);
1315 return false;
1316 };
1317 if (theta.size() < 2 || shared_distance_neg_per_pt.empty()) return fail();
1318 const auto n_pairtypes =
1319 static_cast<Eigen::Index>(shared_distance_neg_per_pt.size());
1320 const auto n_length_scales = lengthScale.size();
1321 if (n_length_scales <= 0 || theta.size() < 1 + n_length_scales)
1322 return fail();
1323 const bool scalar_length = n_length_scales == 1;
1324 if (!scalar_length && n_length_scales != n_pairtypes) return fail();
1325
1326 const Eigen::Index rows = shared_distance_neg_per_pt[0].rows();
1327 const Eigen::Index cols = shared_distance_neg_per_pt[0].cols();
1328 if (kernel_out.rows() != rows || kernel_out.cols() != cols) {
1329 kernel_out.resize(rows, cols);
1330 }
1331 kernel_out.setZero();
1332 for (Eigen::Index pt = 0; pt < n_pairtypes; ++pt) {
1333 const auto& q_pt =
1334 shared_distance_neg_per_pt[static_cast<std::size_t>(pt)];
1335 if (q_pt.rows() != rows || q_pt.cols() != cols) return fail();
1336 const double log_length = scalar_length ? theta(1) : theta(1 + pt);
1337 const double inv_length_sq = numerics::exp(-2.0 * log_length);
1338 kernel_out.noalias() += inv_length_sq * q_pt;
1339 }
1340 scaledExpOfHalfNegative(kernel_out.data(), kernel_out.size(),
1341 numerics::exp(theta(0)));
1342 return true;
1343}

◆ cacheDistances()

void gpr::SexpatCF::cacheDistances ( const Coord & x1,
const Coord & x2 )

Pre-compute and cache inverse distances for the given positions.

Call once before an optimization loop. Subsequent covariance matrix evaluations will use the cached 1/r values, avoiding redundant coordinate extractions and norm computations.

Definition at line 2916 of file SexpatCF.cpp.

2917{
2918 dist_calculator_.cacheInverseDistances(x1, x2, conf_info);
2919}

◆ calculateCovarianceMatrix()

void gpr::SexpatCF::calculateCovarianceMatrix ( const Coord & x1,
Coord & x2,
FieldMatrixd & C )

Evaluate covariance matrix between two input vectors.

The function takes in covariance function of a Gaussian process GP and two matrixes TX and X that contain input vectors to GP. Returns covariance matrix C. Every element ij of C contains covariance between inputs i in TX and j in X. This is a mandatory subfunction used for example in prediction and energy computations.

Parameters
x1Input configurations supplying the rows of the covariance.
x2Input configurations supplying the columns of the covariance.
COutput covariance matrix between x1 and x2.

Definition at line 461 of file SexpatCF.cpp.

463{
464 if (compose_operators_) {
465 if (auto op = assembledOperator()) {
466 if (x2.size() == 0) x2 = x1;
467 if (usesManifoldChart()) {
468 noteManifoldGeometryRows(x1.rows(), x2.rows());
469 }
470 C = op->covarianceBlock(x1, x2, -1, -1);
471 return;
472 }
473 }
474 // Based on equation (2.3)
475 if (x2.size() == 0) x2 = x1;
476
477 FieldMatrixd dist_field;
478
479 // Fused path: get squared distances directly, skip sqrt + square roundtrip
480 dist_calculator_.dist_at_cached_sq(x1, x2, conf_info, lengthScale,
481 dist_field);
482
483 // dist_field contains squared distances. The padded packet exponential
484 // below is the same one as the shared kernel: an entry does not depend
485 // on where it sits or on the length modulo the packet. There is no
486 // separate Highway hn::Exp tail on this path.
487 C.resize(dist_field.rows(), dist_field.cols());
488 if (C.size() > 0) {
489 std::copy_n(dist_field.data(), static_cast<std::size_t>(C.size()),
490 C.data());
491 }
492 scaledExpOfHalfNegative(C.data(), C.size(), magnSigma2);
493}
std::shared_ptr< const KernelOperator > assembledOperator() const
The configured base and optional additive heat component.
Definition SexpatCF.cpp:585

◆ calculateDirectionalCovarianceMatrix()

void gpr::SexpatCF::calculateDirectionalCovarianceMatrix ( const Coord & x1,
Coord & x2,
const Eigen::VectorXd & direction,
FieldMatrixd & first,
FieldMatrixd & second )

Evaluate the directional first and second derivatives of the covariance matrix along a parameter-space direction.

The direction is expressed in the packed log-parameter coordinates returned by combineParameters().

Definition at line 2392 of file SexpatCF.cpp.

2395{
2396 if (usesManifoldChart()) {
2397 if (x2.size() == 0) x2 = x1;
2398 chartDirectionalBlocks(x1, x2, -1, -1, direction, first, second);
2399 return;
2400 }
2401
2402 first.resize(0, 0);
2403 second.resize(0, 0);
2404 if (lengthScale.size() == 0) return;
2405
2406 FieldMatrixd K = evaluate_kernel_matrix(*this, x1, x2);
2407 std::vector<FieldMatrixd> dist_pt;
2408 dist_calculator_.dist_at_vec(x1, x2, conf_info, lengthScale, dist_pt);
2409
2410 const auto dirs = unpack_direction(*this, direction);
2411 FieldMatrixd k1, k2;
2412 compute_kernel_prefactors(K, dist_pt, dirs.length_dir, dirs.sigma_dir, k1,
2413 k2);
2414
2415 first = (K.array() * k1.array()).matrix();
2416 second = (K.array() * k2.array()).matrix();
2417}

◆ calculateDirectionalCovarianceMatrixFromGeometry()

bool gpr::SexpatCF::calculateDirectionalCovarianceMatrixFromGeometry ( const FieldMatrixd & shared_kernel,
const std::vector< FieldMatrixd > & shared_distance_neg_per_pt,
const Eigen::VectorXd & theta,
const Eigen::VectorXd & direction,
FieldMatrixd & first,
FieldMatrixd & second ) const
nodiscard

Directional first and second derivatives for the Kff block from shared training geometry.

Definition at line 1611 of file SexpatCF.cpp.

1616{
1617 first.resize(0, 0);
1618 second.resize(0, 0);
1619
1620 bool scalar_length = false;
1621 Eigen::Index n_pt = 0;
1622 FieldMatrixd k1, k2;
1623 if (!directional_kernel_prefactors(
1624 *this, shared_kernel, shared_distance_neg_per_pt, theta, direction,
1625 scalar_length, n_pt, k1, k2)) {
1626 return false;
1627 }
1628 (void)scalar_length;
1629 (void)n_pt;
1630
1631 first = (shared_kernel.array() * k1.array()).matrix();
1632 second = (shared_kernel.array() * k2.array()).matrix();
1633 return true;
1634}

◆ calculateDirectionalCovarianceMatrixWithDerivatives()

void gpr::SexpatCF::calculateDirectionalCovarianceMatrixWithDerivatives ( const Coord & x1,
Coord & x2,
FieldMatrixIdx & dims,
const Eigen::VectorXd & direction,
FieldMatrixd & first,
FieldMatrixd & second )

Evaluate directional first and second derivatives of the derivative-vs-value covariance block.

Definition at line 2419 of file SexpatCF.cpp.

2422{
2423 if (usesManifoldChart()) {
2424 if (x2.size() == 0) x2 = x1;
2425 chartDirectionalBlocks(x1, x2, dims(0) - 1, -1, direction, first,
2426 second);
2427 return;
2428 }
2429
2430 first.resize(0, 0);
2431 second.resize(0, 0);
2432 if (lengthScale.size() == 0) return;
2433
2434 if (x2.size() == 0) x2 = x1;
2435
2436 aux::Gradient grad_calculator;
2437 grad_calculator.setFarFieldRadius(far_field_radius_);
2438 Derivatives<std::vector<FieldMatrixd>> derivatives;
2439 Derivatives<std::vector<FieldMatrixd>> derivatives_pt;
2440 const uint8_t calc_options =
2442
2443 grad_calculator.calculateDerivativesSameDim(x1, x2, conf_info, lengthScale,
2444 dims, calc_options, derivatives,
2445 derivatives_pt);
2446
2447 std::vector<FieldMatrixd> dist_pt;
2448 dist_calculator_.dist_at_vec(x1, x2, conf_info, lengthScale, dist_pt);
2449 FieldMatrixd K = evaluate_kernel_matrix(*this, x1, x2);
2450
2451 const auto dirs = unpack_direction(*this, direction);
2452 FieldMatrixd k1, k2;
2453 compute_kernel_prefactors(K, dist_pt, dirs.length_dir, dirs.sigma_dir, k1,
2454 k2);
2455
2456 FieldMatrixd d1_first;
2457 FieldMatrixd d1_second;
2458 accumulate_directional_pt_fields(derivatives_pt.D1, dirs.length_dir, 2.0,
2459 -4.0, d1_first, d1_second);
2460
2461 const auto& D1 = derivatives.D1[0];
2462 first = (-0.5 * K.array() * (k1.array() * D1.array() + d1_first.array()))
2463 .matrix();
2464 second = (-0.5 * K.array() *
2465 (k2.array() * D1.array() + 2.0 * k1.array() * d1_first.array() +
2466 d1_second.array()))
2467 .matrix();
2468}

◆ calculateDirectionalCovarianceMatrixWithDerivatives2()

void gpr::SexpatCF::calculateDirectionalCovarianceMatrixWithDerivatives2 ( const Coord & x1,
Coord & x2,
FieldMatrixIdx & dims1,
FieldMatrixIdx & dims2,
const Eigen::VectorXd & direction,
FieldMatrixd & first,
FieldMatrixd & second )

Evaluate directional first and second derivatives of the derivative-vs-derivative covariance block.

Definition at line 2470 of file SexpatCF.cpp.

2473{
2474 if (usesManifoldChart()) {
2475 if (x2.size() == 0) x2 = x1;
2476 chartDirectionalBlocks(x1, x2, dims1(0) - 1, dims2(0) - 1, direction,
2477 first, second);
2478 return;
2479 }
2480
2481 first.resize(0, 0);
2482 second.resize(0, 0);
2483 if (lengthScale.size() == 0) return;
2484
2485 if (x2.size() == 0) x2 = x1;
2486
2487 aux::Gradient grad_calculator;
2488 grad_calculator.setFarFieldRadius(far_field_radius_);
2489 Derivatives<std::vector<FieldMatrixd>> derivatives;
2490 Derivatives<std::vector<FieldMatrixd>> derivatives_pt;
2491 const uint8_t calc_options =
2495
2496 if (dims1(0, 0) == dims2(0, 0)) {
2497 grad_calculator.calculateDerivativesSameDim(
2498 x1, x2, conf_info, lengthScale, dims1, calc_options, derivatives,
2499 derivatives_pt);
2500 } else {
2501 grad_calculator.calculateDerivativesDiffDim(
2502 x1, x2, conf_info, lengthScale, dims1, dims2, calc_options,
2503 Directions::x, derivatives, derivatives_pt);
2504 }
2505
2506 std::vector<FieldMatrixd> dist_pt;
2507 dist_calculator_.dist_at_vec(x1, x2, conf_info, lengthScale, dist_pt);
2508 FieldMatrixd K = evaluate_kernel_matrix(*this, x1, x2);
2509
2510 const auto dirs = unpack_direction(*this, direction);
2511 FieldMatrixd k1, k2;
2512 compute_kernel_prefactors(K, dist_pt, dirs.length_dir, dirs.sigma_dir, k1,
2513 k2);
2514
2515 FieldMatrixd d1_first, d1_second, d2_first, d2_second, d12_first,
2516 d12_second;
2517 accumulate_directional_pt_fields(derivatives_pt.D1, dirs.length_dir, 2.0,
2518 -4.0, d1_first, d1_second);
2519 accumulate_directional_pt_fields(derivatives_pt.D2, dirs.length_dir, 2.0,
2520 -4.0, d2_first, d2_second);
2521 accumulate_directional_pt_fields(derivatives_pt.D12, dirs.length_dir, 2.0,
2522 -4.0, d12_first, d12_second);
2523
2524 const auto& D1 = derivatives.D1[0];
2525 const auto& D2 = derivatives.D2[0];
2526 const auto& D12 = derivatives.D12[0];
2527
2528 const FieldMatrixd base =
2529 (-0.5 * D12.array() + 0.25 * D1.array() * D2.array()).matrix();
2530 const FieldMatrixd base_first =
2531 (-0.5 * d12_first.array() +
2532 0.25 * (d1_first.array() * D2.array() + D1.array() * d2_first.array()))
2533 .matrix();
2534 const FieldMatrixd base_second =
2535 (-0.5 * d12_second.array() +
2536 0.25 * (d1_second.array() * D2.array() +
2537 2.0 * d1_first.array() * d2_first.array() +
2538 D1.array() * d2_second.array()))
2539 .matrix();
2540
2541 first =
2542 (K.array() * (k1.array() * base.array() + base_first.array())).matrix();
2543 second = (K.array() *
2544 (k2.array() * base.array() +
2545 2.0 * k1.array() * base_first.array() + base_second.array()))
2546 .matrix();
2547}
@ x
Definition Enums.h:28

◆ calculateDirectionalCovarianceMatrixWithDerivatives2FromGeometry()

bool gpr::SexpatCF::calculateDirectionalCovarianceMatrixWithDerivatives2FromGeometry ( const CrossBlockGeometry & geometry,
const FieldMatrixd & shared_kernel,
const std::vector< FieldMatrixd > & shared_distance_neg_per_pt,
const Eigen::VectorXd & theta,
const Eigen::VectorXd & direction,
FieldMatrixd & first,
FieldMatrixd & second ) const
nodiscard

Directional first and second derivatives for a D/Kdf2 block from shared training geometry.

Definition at line 1678 of file SexpatCF.cpp.

1683{
1684 first.resize(0, 0);
1685 second.resize(0, 0);
1686 if (!geometry.valid ||
1687 geometry.derivative_options !=
1690 return false;
1691 }
1692
1693 bool scalar_length = false;
1694 Eigen::Index n_pt = 0;
1695 FieldMatrixd k1, k2;
1696 if (!directional_kernel_prefactors(
1697 *this, shared_kernel, shared_distance_neg_per_pt, theta, direction,
1698 scalar_length, n_pt, k1, k2)) {
1699 return false;
1700 }
1701
1702 const auto dirs = unpack_direction(*this, direction);
1703 FieldMatrixd d1, d1_first, d1_second;
1704 FieldMatrixd d2, d2_first, d2_second;
1705 FieldMatrixd d12, d12_first, d12_second;
1706 const Eigen::Index rows = shared_kernel.rows();
1707 const Eigen::Index cols = shared_kernel.cols();
1708 if (!accumulate_directional_geometry_field(
1709 geometry.d1, theta, dirs.length_dir, scalar_length, n_pt, rows,
1710 cols, d1, d1_first, d1_second) ||
1711 !accumulate_directional_geometry_field(
1712 geometry.d2, theta, dirs.length_dir, scalar_length, n_pt, rows,
1713 cols, d2, d2_first, d2_second) ||
1714 !accumulate_directional_geometry_field(
1715 geometry.d12, theta, dirs.length_dir, scalar_length, n_pt, rows,
1716 cols, d12, d12_first, d12_second)) {
1717 return false;
1718 }
1719
1720 const FieldMatrixd base =
1721 (-0.5 * d12.array() + 0.25 * d1.array() * d2.array()).matrix();
1722 const FieldMatrixd base_first =
1723 (-0.5 * d12_first.array() +
1724 0.25 * (d1_first.array() * d2.array() + d1.array() * d2_first.array()))
1725 .matrix();
1726 const FieldMatrixd base_second =
1727 (-0.5 * d12_second.array() +
1728 0.25 * (d1_second.array() * d2.array() +
1729 2.0 * d1_first.array() * d2_first.array() +
1730 d1.array() * d2_second.array()))
1731 .matrix();
1732
1733 const FieldMatrixd& active_kernel = shared_kernel;
1734 first = (active_kernel.array() *
1735 (k1.array() * base.array() + base_first.array()))
1736 .matrix();
1737 second = (active_kernel.array() *
1738 (k2.array() * base.array() +
1739 2.0 * k1.array() * base_first.array() + base_second.array()))
1740 .matrix();
1741 return true;
1742}

◆ calculateDirectionalCovarianceMatrixWithDerivativesFromGeometry()

bool gpr::SexpatCF::calculateDirectionalCovarianceMatrixWithDerivativesFromGeometry ( const CrossBlockGeometry & geometry,
const FieldMatrixd & shared_kernel,
const std::vector< FieldMatrixd > & shared_distance_neg_per_pt,
const Eigen::VectorXd & theta,
const Eigen::VectorXd & direction,
FieldMatrixd & first,
FieldMatrixd & second ) const
nodiscard

Directional first and second derivatives for a Kdf block from shared training geometry.

Definition at line 1636 of file SexpatCF.cpp.

1641{
1642 first.resize(0, 0);
1643 second.resize(0, 0);
1644 if (!geometry.valid ||
1645 geometry.derivative_options != OptionsForGradCalculation::D1) {
1646 return false;
1647 }
1648
1649 bool scalar_length = false;
1650 Eigen::Index n_pt = 0;
1651 FieldMatrixd k1, k2;
1652 if (!directional_kernel_prefactors(
1653 *this, shared_kernel, shared_distance_neg_per_pt, theta, direction,
1654 scalar_length, n_pt, k1, k2)) {
1655 return false;
1656 }
1657
1658 const auto dirs = unpack_direction(*this, direction);
1659 FieldMatrixd d1, d1_first, d1_second;
1660 if (!accumulate_directional_geometry_field(
1661 geometry.d1, theta, dirs.length_dir, scalar_length, n_pt,
1662 shared_kernel.rows(), shared_kernel.cols(), d1, d1_first,
1663 d1_second)) {
1664 return false;
1665 }
1666
1667 const FieldMatrixd& active_kernel = shared_kernel;
1668 first = (-0.5 * active_kernel.array() *
1669 (k1.array() * d1.array() + d1_first.array()))
1670 .matrix();
1671 second = (-0.5 * active_kernel.array() *
1672 (k2.array() * d1.array() + 2.0 * k1.array() * d1_first.array() +
1673 d1_second.array()))
1674 .matrix();
1675 return true;
1676}

◆ calculateDirectionalLogPriorCurvature()

double gpr::SexpatCF::calculateDirectionalLogPriorCurvature ( const Eigen::VectorXd & direction) const

Evaluate the second directional derivative of log p(theta) along the packed log-parameter direction.

Definition at line 2549 of file SexpatCF.cpp.

2551{
2552 const auto& active_lengths = getLengthScaleRef();
2553 if (direction.size() == 0) return 0.0;
2554
2555 const auto dirs = unpack_direction(*this, direction);
2556
2557 if (!usesClassicJointEnergyForcePrior(model_profile_)) {
2558 if (use_hierarchical_prior_) {
2559 const Eigen::Index expected = 1 + active_lengths.size();
2560 if (hierarchical_mu_log_.size() != expected) return 0.0;
2561 double curvature = 0.0;
2562 const double s2_m = hierarchicalPriorVariance(0);
2563 if (s2_m > 0.0) curvature -= dirs.sigma_dir * dirs.sigma_dir / s2_m;
2564 for (Eigen::Index i = 0; i < active_lengths.size(); ++i) {
2565 const double s2 = hierarchicalPriorVariance(i + 1);
2566 if (!(s2 > 0.0)) continue;
2567 const double d = expanded_length_direction(dirs.length_dir, i);
2568 curvature -= lengthPriorWeight(i) * d * d / s2;
2569 }
2570 return curvature;
2571 }
2572 if (use_pc_lengthscale_prior_ &&
2573 pc_lambda_.size() == active_lengths.size()) {
2574 double curvature = 0.0;
2575 for (Eigen::Index i = 0; i < active_lengths.size(); ++i) {
2576 const double rho = *(active_lengths.data() + i);
2577 const double lambda = pc_lambda_(i);
2578 const double d = expanded_length_direction(dirs.length_dir, i);
2579 if (rho > 0.0 && lambda > 0.0) {
2580 curvature -= lengthPriorWeight(i) * lambda * d * d / rho;
2581 }
2582 }
2583 return curvature;
2584 }
2585 return 0.0;
2586 }
2587
2588 double curvature = 0.0;
2589
2590 PriorGaussian prior_gaussian;
2591 PriorSqrtt prior_sqrtt;
2592 prior_gaussian.setParameters(prior_parameters_gaussian);
2593 prior_sqrtt.setParameters(prior_parameters_sqrtt);
2594
2595 if (use_lognormal_magn_prior_ && prior_parameters_lognormal.getS2() > 0.0 &&
2596 magnSigma2 > 0.0 && std::isfinite(magnSigma2)) {
2597 curvature -= dirs.sigma_dir * dirs.sigma_dir /
2598 prior_parameters_lognormal.getS2();
2599 } else if (magnSigma2 > 0.0 && prior_sqrtt.getNu() > 0.0 &&
2600 prior_sqrtt.getS2() > 0.0) {
2601 Dual2 sigma = direction_dual(magnSigma2, dirs.sigma_dir);
2602 Dual2 sqrt_sigma = sqrt_dual(sigma);
2603 const double nu = prior_sqrtt.getNu();
2604 const double mu = prior_sqrtt.getMu();
2605 const double s2 = prior_sqrtt.getS2();
2606
2607 Dual2 centered = sqrt_sigma - constant_dual(mu);
2608 Dual2 log_prior =
2609 constant_dual(numerics::lgamma(0.5 * (nu + 1)) -
2610 numerics::lgamma(0.5 * nu) -
2611 0.5 * numerics::log(nu * M_PI * s2)) -
2612 0.5 * (nu + 1) *
2613 log_dual(constant_dual(1.0) +
2614 centered * centered / constant_dual(nu * s2)) -
2615 log_dual(2.0 * sqrt_sigma) + log_dual(sigma);
2616 curvature += log_prior.second;
2617 }
2618
2619 const double gauss_s2 = prior_gaussian.getS2();
2620 const double gauss_mu = prior_gaussian.getMu();
2621 const bool anchors_ready =
2622 use_hierarchical_prior_ &&
2623 hierarchical_mu_log_.size() == 1 + active_lengths.size();
2624 if (gauss_s2 > 0.0 || anchors_ready) {
2625 for (Eigen::Index i = 0; i < active_lengths.size(); ++i) {
2626 const double dir = expanded_length_direction(dirs.length_dir, i);
2627 const double value = *(active_lengths.data() + i);
2628 const double s2_anchor = hierarchicalPriorVariance(i + 1);
2629 if (anchors_ready && hierarchicalAnchored(i) && s2_anchor > 0.0) {
2630 // Log-Gaussian in log space: the curvature along the
2631 // direction is -d^2 / s2.
2632 curvature -= lengthPriorWeight(i) * dir * dir / s2_anchor;
2633 continue;
2634 }
2635 if (!(gauss_s2 > 0.0)) continue;
2636 Dual2 ell = direction_dual(value, dir);
2637 Dual2 centered = ell - constant_dual(gauss_mu);
2638 Dual2 log_prior =
2639 constant_dual(-0.5 * (numerics::log(2.0 * M_PI) +
2640 numerics::log(gauss_s2))) -
2641 0.5 * centered * centered / constant_dual(gauss_s2) +
2642 log_dual(ell);
2643 curvature += lengthPriorWeight(i) * log_prior.second;
2644 }
2645 }
2646
2647 return curvature;
2648}
double hierarchicalPriorVariance(Eigen::Index n) const noexcept
Variance of packed parameter ~n~ under the hierarchical prior.
Definition SexpatCF.h:799
FieldMatrixd & getLengthScaleRef()
Definition SexpatCF.inl:58
bool hierarchicalAnchored(Eigen::Index n) const noexcept
Definition SexpatCF.h:792
double lgamma(double x) noexcept
double log(double x) noexcept
bool usesClassicJointEnergyForcePrior(GPModelProfile profile) noexcept
Definition Structures.h:206

◆ calculateGradOfCovMatrix()

void gpr::SexpatCF::calculateGradOfCovMatrix ( const Coord & x1,
Coord & x2,
std::vector< FieldMatrixd > & DKff )

Evaluate gradient of covariance function with respect to the parameters.

The function takes a covariance function structure GPCF, a matrix X of input vectors and returns DKff, the gradients of covariance matrix Kff = k(X,X) with respect to th (cell array with matrix elements). This is a mandatory subfunction used for example in gradient computations.

Parameters
x1Input configurations for the first covariance argument.
x2Input configurations for the second covariance argument.
DKffOutput covariance-matrix gradients with respect to the covariance hyperparameters.

Definition at line 2110 of file SexpatCF.cpp.

2112{
2113 if (usesManifoldChart()) {
2114 if (x2.size() == 0) x2 = x1;
2115 DKff = {
2116 chartParameterBlock(
2117 x1, x2, -1, -1,
2119 chartParameterBlock(
2120 x1, x2, -1, -1,
2122 return;
2123 }
2124
2125 io::ErrorManager err;
2126 FieldMatrixd dist;
2127 std::vector<FieldMatrixd> dist_pt;
2128 FieldMatrixd K, DK_l;
2129 std::vector<Index_t> i1;
2130
2131 DKff.clear();
2132
2133 if (x2.size() == 0) x2 = x1;
2134
2135 // Evaluate: DKff{1} = d Kff / d magnSigma2
2136 // DKff{2} = d Kff / d lengthScale
2137 // NOTE! Here we have already taken into account that the parameters
2138 // are transformed through log() and thus dK/dlog(p) = p * dK/dp
2139 // evaluate the gradient for training covariance
2140 if (x1.cols() != x2.cols()) {
2141 err << "gpcf_sexp -> _ghyper: The number of columns in x and x2 has to "
2142 "be the same.\n";
2143 }
2144
2145 dist_calculator_.dist_at_cached_sq(x1, x2, conf_info, lengthScale, dist);
2146
2147 // K = magnSigma2 * exp(-0.5 * dist²). Same untruncated k as ginput.
2148 K = (magnSigma2 * (-0.5 * dist.array()).exp()).matrix();
2149 DKff.push_back(K);
2150
2151 if (lengthScale.size() == 1) {
2152 // Isotropic case. K = magnSigma2 * exp(-0.5 * r^2 / l^2) and the
2153 // packed parameter is log(l), so
2154 // dK/dlog(l) = K * (r^2 / l^2) = +K .* dist2
2155 // (dist already stores the lengthscale-scaled squared distance).
2156 // A 60-digit evaluation of the marginal-likelihood gradient on
2157 // the petmad tile fixture pins the positive sign: the negated
2158 // block makes the reported gradient the exact negative of the
2159 // finite difference of the energy this class itself computes.
2160 DK_l = (K.array() * dist.array()).matrix();
2161 DKff.push_back(std::move(DK_l));
2162 } else {
2163 dist_calculator_.dist_at_vec(x1, x2, conf_info, lengthScale, dist_pt);
2164
2165 // Per-pairtype: dK/dlog(l_pt) = +K .* (r_pt^2 / l_pt^2). Unlike
2166 // dist_at_cached_sq above (positive squared distances),
2167 // dist_at_vec returns the NEGATED per-pairtype squared
2168 // distances, so the leading minus restores the positive
2169 // derivative (untruncated K, exp form); the MATLAB reference
2170 // values pin the positive sign.
2171 //
2172 // K already holds magnSigma2 * exp(-0.5 * dist^2). Reuse it rather
2173 // than writing the exp again: (-magnSigma2 * e) * d and (-(magnSigma2
2174 // * e)) * d are the same value under IEEE-754, since negation is
2175 // exact. The previous form bound the exp to `auto`, which keeps it an
2176 // unevaluated Eigen expression, so the transcendental was recomputed
2177 // over the whole matrix once per pairtype.
2178 for (Index_t m = 0; m < conf_info.n_pt; ++m) {
2179 DK_l = (-K.array() * dist_pt[m].array()).matrix();
2180 DKff.push_back(std::move(DK_l));
2181 }
2182 }
2183}
uint32_t Index_t
Definition Macros.h:17

◆ calculateGradOfCovMatrixFromGeometry()

bool gpr::SexpatCF::calculateGradOfCovMatrixFromGeometry ( const FieldMatrixd & shared_kernel,
const std::vector< FieldMatrixd > & shared_distance_neg_per_pt,
const Eigen::VectorXd & theta,
std::vector< FieldMatrixd > & DKff,
const std::vector< Eigen::Index > * parameter_indices = nullptr ) const
nodiscard

Geometry-path replacement for calculateGradOfCovMatrix. Produces DKff[0] = K (untruncated kernel), DKff[1+pt] = K * inv_l_pt^2 * shared_distance_neg[pt] (== -K * dist_pt_actual in the legacy negated sign convention). Scalar-length case collapses to a single DKff[1] entry that sums across pairtypes. An optional nonempty parameter list selects output blocks in the given order. All parameters still contribute to the kernel and its Cartesian derivatives; only the requested hyperparameter derivatives are formed.

Definition at line 1437 of file SexpatCF.cpp.

1442{
1443 const auto fail = [&DKff]() {
1444 DKff.clear();
1445 return false;
1446 };
1447 if (theta.size() < 2 || shared_distance_neg_per_pt.empty()) return fail();
1448 const auto n_pt =
1449 static_cast<Eigen::Index>(shared_distance_neg_per_pt.size());
1450 const auto n_length_scales = lengthScale.size();
1451 if (n_length_scales <= 0 || theta.size() < 1 + n_length_scales)
1452 return fail();
1453 const bool scalar_length = n_length_scales == 1;
1454 if (!scalar_length && n_length_scales != n_pt) return fail();
1455
1456 const Eigen::Index rows = shared_kernel.rows();
1457 const Eigen::Index cols = shared_kernel.cols();
1458 for (const auto& distance: shared_distance_neg_per_pt) {
1459 if (distance.rows() != rows || distance.cols() != cols) return fail();
1460 }
1461
1462 const Eigen::Index parameter_count = scalar_length ? 2 : 1 + n_pt;
1463 if (!valid_gradient_parameter_selection(parameter_indices, parameter_count))
1464 return fail();
1465 const std::size_t n_blocks =
1466 parameter_indices != nullptr
1467 ? parameter_indices->size()
1468 : static_cast<std::size_t>(parameter_count);
1469 if (!resize_geometry_gradient_blocks(DKff, n_blocks, rows, cols)) {
1470 return fail();
1471 }
1472
1473 const FieldMatrixd& K = shared_kernel;
1474
1475 // dK/dlog(l) = +K * (r^2 / l^2). shared_distance_neg_per_pt stores
1476 // the NEGATION of dist_at_vec's output, and dist_at_vec itself
1477 // returns negated squared distances, so the stored field is the
1478 // POSITIVE squared distance: the scalar branch contracts it with a
1479 // positive sign (the live calculateGradOfCovMatrix isotropic branch
1480 // and the energy's Richardson finite difference pin this sign), and
1481 // the ARD branch keeps the positive product it already forms.
1482 for (std::size_t out = 0; out < n_blocks; ++out) {
1483 const Eigen::Index parameter = parameter_indices != nullptr
1484 ? (*parameter_indices)[out]
1485 : static_cast<Eigen::Index>(out);
1486 if (parameter == 0) {
1487 DKff[out] = K;
1488 } else if (scalar_length) {
1489 const double inv_length_sq = numerics::exp(-2.0 * theta(1));
1490 FieldMatrixd dist_sq = FieldMatrixd::Zero(rows, cols);
1491 for (Eigen::Index pt = 0; pt < n_pt; ++pt) {
1492 dist_sq.noalias() +=
1493 shared_distance_neg_per_pt[static_cast<std::size_t>(pt)];
1494 }
1495 DKff[out] = (K.array() * inv_length_sq * dist_sq.array()).matrix();
1496 } else {
1497 const Eigen::Index pt = parameter - 1;
1498 const double inv_length_sq = numerics::exp(-2.0 * theta(1 + pt));
1499 DKff[out] =
1500 (K.array() * inv_length_sq *
1501 shared_distance_neg_per_pt[static_cast<std::size_t>(pt)]
1502 .array())
1503 .matrix();
1504 }
1505 }
1506 return true;
1507}

◆ calculateGradOfCovMatrixWithDerivatives()

void gpr::SexpatCF::calculateGradOfCovMatrixWithDerivatives ( const Coord & x1,
Coord & x2,
FieldMatrixIdx & dims,
std::vector< FieldMatrixd > & DKff )

Evaluate gradient of covariance function, of which has been taken partial derivative with respect to x1, with respect to parameters.

The function takes a covariance function structure GPCF, a matrix X of input vectors and returns DKff, the gradients of derivatived covariance matrix dK(df,f)/dhyp = d(d k(X,X)/dx)/dhyp, with respect to the parameters.

Evaluate: DKff{1:m} = d Kff / d magnSigma2 DKff{m+1:2m} = d Kff / d lengthScale_m m is the dimension of inputs. If ARD is used, then multiple lengthScales. This subfunction is needed when using derivative observations.

 dims - is a vector of input dimensions with respect to which the
        derivatives of the covariance function have been calculated
        [by default dims=1:size(x,2)]

Note! When coding the derivatives of the covariance function, remember to double check them. See gp_cov for lines of code to check the matrices

Parameters
x1Configurations supplying the first covariance argument.
x2Configurations supplying the second covariance argument.
dimsCoordinate-dimension indices of the derivative observations.
DKffOutput covariance-derivative blocks for each hyperparameter.

Definition at line 2185 of file SexpatCF.cpp.

2188{
2189 if (usesManifoldChart()) {
2190 if (x2.size() == 0) x2 = x1;
2191 DKff.clear();
2192 for (const auto derivative:
2195 for (Eigen::Index i = 0; i < dims.size(); ++i)
2196 DKff.push_back(
2197 chartParameterBlock(x1, x2, dims(i) - 1, -1, derivative));
2198 return;
2199 }
2200
2201 const PrimitiveKernelScope primitive(compose_operators_);
2202
2203 // Scratch that the parallel loop only reads or writes must be shared.
2204 // thread_local would give each worker an empty copy of the master's
2205 // distances and derivatives. Cdm and the gradient calculator stay
2206 // thread_local: they are filled before the team starts.
2207 thread_local std::vector<FieldMatrixd> Cdm;
2208 thread_local aux::Gradient grad_calculator;
2209 grad_calculator.setFarFieldRadius(far_field_radius_);
2210 std::vector<FieldMatrixd> dist_pt;
2211 std::vector<FieldMatrixd> DK_pt;
2212 Derivatives<std::vector<FieldMatrixd>> derivatives;
2213 Derivatives<std::vector<FieldMatrixd>> derivatives_pt;
2214 thread_local FieldMatrixd DK;
2215 // derivatives.* are reserve+push_back'd per dimension, so they must start
2216 // empty. derivatives_pt.* are sized and zeroed in full by
2217 // resizeDerivativeFields, so clearing them here only throws away storage
2218 // that the next call reallocates.
2219 derivatives.D1.clear();
2220 derivatives.D2.clear();
2221 derivatives.D12.clear();
2222 uint8_t calc_options =
2224
2225 DKff.clear();
2226
2227 if (x2.size() == 0) x2 = x1;
2228
2229 // ginput4 evaluates exp(-0.5 * d^2) over exactly these distances; take
2230 // its factor rather than repeating the transcendental, which also makes
2231 // the dist_at_cached_sq that only fed it unnecessary here.
2232 ExpDistArray expdist;
2233 ginput4(x1, x2, dims, Cdm, &expdist);
2234
2235 for (Index_t n = 0; n < Cdm.size(); ++n) {
2236 DKff.push_back(std::move(Cdm[n]));
2237 }
2238
2239 dist_calculator_.dist_at_vec(x1, x2, conf_info, lengthScale, dist_pt);
2240
2241 // Pair-type derivative fields sum every coordinate of one
2242 // calculateDerivativesSameDim call. Ask for one coordinate at a time
2243 // so each length-scale block is that coordinate alone. One coordinate
2244 // is the call the training gradient makes, and it runs the same
2245 // product as before.
2246 const auto n_dims = static_cast<Index_t>(dims.size());
2247 const auto n_pt = conf_info.n_pt;
2248 DK_pt.resize(n_dims * n_pt);
2249 FieldMatrixIdx one_dim(1, 1);
2250 for (Index_t n = 0; n < n_dims; ++n) {
2251 one_dim(0, 0) = dims(n);
2252 derivatives.D1.clear();
2253 grad_calculator.calculateDerivativesSameDim(
2254 x1, x2, conf_info, lengthScale, one_dim, calc_options, derivatives,
2255 derivatives_pt);
2256 // The SCG assembly stays on the calling thread. A team around this
2257 // product made the one-thread train slower than the base process.
2258 // The local-oracle path still uses its own gate.
2259#if defined(USE_OPENMP) || defined(GPR_OPENMP_LOCAL_ORACLE)
2260#pragma omp parallel for schedule(static) if (sexpat_local_oracle_active)
2261#endif
2262 for (Index_t pt = 0; pt < n_pt; ++pt) {
2263 DK_pt[n * n_pt + pt] =
2264 (magnSigma2 * expdist *
2265 (-derivatives_pt.D1[pt].array() +
2266 0.5 * derivatives.D1[0].array() * dist_pt[pt].array()))
2267 .matrix();
2268 }
2269 }
2270
2271 if (lengthScale.size() == 1 && n_pt > 1) {
2272 for (Index_t n = 0; n < n_dims; ++n) {
2273 FieldMatrixd total = DK_pt[n * n_pt];
2274 for (Index_t pt = 1; pt < n_pt; ++pt)
2275 total += DK_pt[n * n_pt + pt];
2276 DKff.push_back(std::move(total));
2277 }
2278 } else {
2279 for (Index_t n = 0; n < n_dims; ++n) {
2280 for (Index_t pt = 0; pt < n_pt; ++pt)
2281 DKff.push_back(DK_pt[n * n_pt + pt]);
2282 }
2283 }
2284}
void ginput4(const Coord &x1, Coord &x2, FieldMatrixIdx &dims, std::vector< FieldMatrixd > &DKff, ExpDistArray *out_expdist=nullptr)
Evaluate gradient of covariance function with respect to x.
Eigen::Array< double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor > ExpDistArray
Calculates covariances between the derivatives.
Definition SexpatCF.h:472
Eigen::Matrix< Index_t, EigenDynamic, EigenDynamic, FieldMatrixStorage > FieldMatrixIdx
Definition Macros.h:29

◆ calculateGradOfCovMatrixWithDerivatives2()

void gpr::SexpatCF::calculateGradOfCovMatrixWithDerivatives2 ( const Coord & x1,
Coord & x2,
FieldMatrixIdx & dims1,
FieldMatrixIdx & dims2,
std::vector< FieldMatrixd > & DKff )

Evaluate gradient of covariance function, of which has been taken partial derivatives with respect to both input variables x1 and x2 with respect to parameters.

The function takes a covariance function structure GPCF, a matrix X of input vectors and returns DKff, the gradients of derivative covariance matrix dK(df,df)/dhyp = d(d^2 k(X1,X2)/dX1dX2)/dhyp with respect to the parameters.

Evaluate: DKff{1-m} = d Kff / d magnSigma2 DKff{m+1-2m} = d Kff / d lengthScale_m m is the dimension of inputs. If ARD is used, then multiple lengthScales. This subfunction is needed when using derivative observations.

Parameters
x1Configurations supplying the first covariance argument.
x2Configurations supplying the second covariance argument.
dims1Coordinate-dimension indices differentiated in x1.
dims2Coordinate-dimension indices differentiated in x2.
DKffOutput second-derivative covariance blocks for each hyperparameter.

Definition at line 2286 of file SexpatCF.cpp.

2289{
2290 if (usesManifoldChart()) {
2291 if (dims1.size() != 1 || dims2.size() != 1)
2292 throw std::invalid_argument(
2293 "chart derivative dimensions must be 1x1");
2294 if (x2.size() == 0) x2 = x1;
2295 DKff.clear();
2296 for (const auto derivative:
2299 DKff.push_back(chartParameterBlock(x1, x2, dims1(0) - 1,
2300 dims2(0) - 1, derivative));
2301 return;
2302 }
2303
2304 const PrimitiveKernelScope primitive(compose_operators_);
2305
2306 // thread_local assembly scratch, the same treatment ginput2/3/4 already
2307 // give their temporaries. These are vectors of Eigen matrices rebuilt on
2308 // every call; as plain locals each call reallocated every block, which is
2309 // where perf attributes ~11% of this path to memmove and memset. Each is
2310 // cleared or fully overwritten below, so reuse is value-identical.
2311 thread_local std::vector<FieldMatrixd> Cdm;
2312 thread_local aux::Gradient grad_calculator;
2313 grad_calculator.setFarFieldRadius(far_field_radius_);
2314 thread_local std::vector<FieldMatrixd> dist_pt;
2315 thread_local std::vector<FieldMatrixd> DK_pt;
2316 thread_local Derivatives<std::vector<FieldMatrixd>> derivatives;
2317 thread_local Derivatives<std::vector<FieldMatrixd>> derivatives_pt;
2318 thread_local std::vector<FieldMatrixd> DKdd;
2319 thread_local FieldMatrixd DK;
2320 // derivatives.* are reserve+push_back'd per dimension, so they must start
2321 // empty. derivatives_pt.* are sized and zeroed in full by
2322 // resizeDerivativeFields, so clearing them here only throws away storage
2323 // that the next call reallocates.
2324 derivatives.D1.clear();
2325 derivatives.D2.clear();
2326 derivatives.D12.clear();
2327 uint8_t calc_options =
2331
2332 DKff.clear();
2333
2334 if (x2.size() == 0) x2 = x1;
2335
2336 // The per-pairtype loop below assigns DK once per derivative dimension and
2337 // pushes a single block afterwards, so with more than one dimension every
2338 // block but the last is computed and dropped. Every call site passes a
2339 // 1x1 dims (GaussianProcessRegression.inl, StudentTProcessRegression.cpp),
2340 // which is the only shape the body is correct for. Refuse anything else
2341 // rather than return a silently truncated result.
2342 if (dims1.size() != 1 || dims2.size() != 1) {
2343 throw std::invalid_argument(
2344 "SexpatCF::calculateGradOfCovMatrixWithDerivatives2 handles one "
2345 "derivative dimension per side; dims1 and dims2 must be 1x1");
2346 }
2347
2348 // Compute the derivative fields first. ginput3 needs D1/D2/D12 over these
2349 // same inputs and this call already asks for them plus the _pt fields, so
2350 // handing them over means the pair is built once instead of twice. The
2351 // direction argument that appears to distinguish the two requests is
2352 // never read (Gradient.cpp), so the shared fields are the same values.
2353 dist_calculator_.dist_at_vec(x1, x2, conf_info, lengthScale, dist_pt);
2354
2355 grad_calculator.calculateDerivativesDiffDim(
2356 x1, x2, conf_info, lengthScale, dims1, dims2, calc_options,
2357 Directions::x, derivatives, derivatives_pt);
2358
2359 // ginput2/ginput3 already evaluate exp(-0.5 * d^2) over exactly these
2360 // distances; take theirs instead of recomputing the transcendental, which
2361 // also makes the dist_at_cached_sq that only fed it unnecessary here.
2362 ExpDistArray expdist;
2363 if (dims1(0, 0) == dims2(0, 0))
2364 ginput2(x1, x2, dims1, DKdd, &expdist);
2365 else
2366 ginput3(x1, x2, dims1, dims2, DKdd, &expdist, &derivatives);
2367
2368 DKff.push_back(std::move(DKdd[0]));
2369
2370 for (Index_t pt = 0; pt < conf_info.n_pt; ++pt) {
2371 for (Eigen::Index n = 0; n < dims1.size(); ++n) {
2372 DK = (magnSigma2 * expdist *
2373 (-derivatives_pt.D12[pt].array() -
2374 0.25 * derivatives.D1[n].array() *
2375 derivatives.D2[n].array() * dist_pt[pt].array() +
2376 0.5 * (derivatives.D1[n].array() *
2377 derivatives_pt.D2[pt].array() +
2378 derivatives.D2[n].array() *
2379 derivatives_pt.D1[pt].array() +
2380 dist_pt[pt].array() * derivatives.D12[n].array())))
2381 .matrix();
2382 }
2383 DKff.push_back(std::move(DK));
2384 }
2385 if (lengthScale.size() == 1 && conf_info.n_pt > 1) {
2386 for (std::size_t pt = 2; pt < DKff.size(); ++pt)
2387 DKff[1] += DKff[pt];
2388 DKff.resize(2);
2389 }
2390}
void ginput2(const Coord &x1, Coord &x2, FieldMatrixIdx &dims, std::vector< FieldMatrixd > &DKff, ExpDistArray *out_expdist=nullptr)
void ginput3(const Coord &x1, Coord &x2, FieldMatrixIdx &dims1, FieldMatrixIdx &dims2, std::vector< FieldMatrixd > &DKff, ExpDistArray *out_expdist=nullptr, const SharedDerivatives *precomputed=nullptr)

◆ calculateGradOfCovMatrixWithDerivatives2FromGeometry()

bool gpr::SexpatCF::calculateGradOfCovMatrixWithDerivatives2FromGeometry ( const CrossBlockGeometry & geometry,
const FieldMatrixd & shared_kernel,
const std::vector< FieldMatrixd > & shared_distance_neg_per_pt,
const Eigen::VectorXd & theta,
std::vector< FieldMatrixd > & DKff,
const std::vector< Eigen::Index > * parameter_indices = nullptr ) const
nodiscard

Geometry-path replacement for calculateGradOfCovMatrixWithDerivatives2 (D and Kdf2 blocks).

Same shape as the original: DKff[0] is the block value at theta (== evaluateCrossBlockGeometryWithSharedKernel options=D1|D2|D12), DKff[1+pt] is the derivative wrt loglength_pt.

Definition at line 1853 of file SexpatCF.cpp.

1858{
1859 const auto fail = [&DKff]() {
1860 DKff.clear();
1861 return false;
1862 };
1863 if (!geometry.valid || theta.size() < 2) return fail();
1864 const auto n_pt =
1865 static_cast<Eigen::Index>(shared_distance_neg_per_pt.size());
1866 const auto n_length_scales = lengthScale.size();
1867 if (n_length_scales <= 0 || theta.size() < 1 + n_length_scales)
1868 return fail();
1869 const bool scalar_length = n_length_scales == 1;
1870 if (!scalar_length && n_length_scales != n_pt) return fail();
1871 if (geometry.d1.size() != static_cast<std::size_t>(n_pt) ||
1872 geometry.d2.size() != static_cast<std::size_t>(n_pt) ||
1873 geometry.d12.size() != static_cast<std::size_t>(n_pt)) {
1874 return fail();
1875 }
1876
1877 const Eigen::Index rows = shared_kernel.rows();
1878 const Eigen::Index cols = shared_kernel.cols();
1879 for (Eigen::Index pt = 0; pt < n_pt; ++pt) {
1880 const auto idx = static_cast<std::size_t>(pt);
1881 if (shared_distance_neg_per_pt[idx].rows() != rows ||
1882 shared_distance_neg_per_pt[idx].cols() != cols ||
1883 geometry.d1[idx].rows() != rows ||
1884 geometry.d1[idx].cols() != cols ||
1885 geometry.d2[idx].rows() != rows ||
1886 geometry.d2[idx].cols() != cols ||
1887 geometry.d12[idx].rows() != rows ||
1888 geometry.d12[idx].cols() != cols) {
1889 return fail();
1890 }
1891 }
1892 const Eigen::Index parameter_count = scalar_length ? 2 : 1 + n_pt;
1893 if (!valid_gradient_parameter_selection(parameter_indices, parameter_count))
1894 return fail();
1895 const std::size_t n_blocks =
1896 parameter_indices != nullptr
1897 ? parameter_indices->size()
1898 : static_cast<std::size_t>(parameter_count);
1899 if (!resize_geometry_gradient_blocks(DKff, n_blocks, rows, cols)) {
1900 return fail();
1901 }
1902
1903 // Per-dim accumulates at actual lengthscale (negated, matching the
1904 // d1_accum_neg / d2_accum_neg / d12_accum_neg pattern).
1905 // Scratch reused across the channel-block pairs of a gradient: the
1906 // routine runs once per pair, tens of thousands of times per gradient.
1907 static thread_local FieldMatrixd d1_neg, d2_neg, d12_neg;
1908 for (FieldMatrixd* scratch: {&d1_neg, &d2_neg, &d12_neg}) {
1909 if (scratch->rows() != rows || scratch->cols() != cols)
1910 scratch->resize(rows, cols);
1911 scratch->setZero();
1912 }
1913 if (!accumulate_per_pt(geometry.d1, d1_neg, theta, scalar_length, n_pt) ||
1914 !accumulate_per_pt(geometry.d2, d2_neg, theta, scalar_length, n_pt) ||
1915 !accumulate_per_pt(geometry.d12, d12_neg, theta, scalar_length, n_pt)) {
1916 return fail();
1917 }
1918
1919 // DKff[0] = block value at theta (matches ginput2 / ginput3 output).
1920 // ginput2/3: DK = magn * exp * (-0.5 * D12[n]_actual
1921 // + 0.25 * D1[n]_actual * D2[n]_actual)
1922 // With evaluateValueInDerivativeField's += convention, per-dim
1923 // accumulators are POSITIVE: D[n]_actual = +d{1,2,12}_neg (the names
1924 // are historical, the values are positive sums).
1925 // => DK[0] = K * (-0.5 * d12_neg + 0.25 * d1_neg * d2_neg)
1926
1927 // For each pairtype, dK/dlog(length_pt). Following calculateGradOfCov-
1928 // MatrixWithDerivatives2: DK_pt = magn * exp * (-D12_pt_actual
1929 // - 0.25 * D1[n]_actual *
1930 // D2[n]_actual *
1931 // dist_pt_actual
1932 // + 0.5 * (D1[n]_actual *
1933 // D2_pt_actual
1934 // + D2[n]_actual *
1935 // D1_pt_actual
1936 // + dist_pt_actual *
1937 // D12[n]_actual))
1938 for (std::size_t out = 0; out < n_blocks; ++out) {
1939 const Eigen::Index parameter = parameter_indices != nullptr
1940 ? (*parameter_indices)[out]
1941 : static_cast<Eigen::Index>(out);
1942 if (parameter == 0) {
1943 DKff[out] = (shared_kernel.array() *
1944 (-0.5 * d12_neg.array() +
1945 0.25 * d1_neg.array() * d2_neg.array()))
1946 .matrix();
1947 continue;
1948 }
1949 if (scalar_length && n_pt > 1) {
1950 // One shared length varies every pairtype at once.
1951 FieldMatrixd distance = FieldMatrixd::Zero(rows, cols);
1952 for (const auto& part: shared_distance_neg_per_pt)
1953 distance += part;
1954 const FieldMatrixd q = numerics::exp(-2.0 * theta(1)) * distance;
1955 DKff[out] = (shared_kernel.array() *
1956 (d12_neg.array() - d1_neg.array() * d2_neg.array() +
1957 q.array() * (-0.5 * d12_neg.array() +
1958 0.25 * d1_neg.array() * d2_neg.array())))
1959 .matrix();
1960 continue;
1961 }
1962 const Eigen::Index pt = parameter - 1;
1963 const double inv_length_sq =
1964 numerics::exp(-2.0 * (scalar_length ? theta(1) : theta(1 + pt)));
1965 const auto& d1_pt = geometry.d1[static_cast<std::size_t>(pt)];
1966 const auto& d2_pt = geometry.d2[static_cast<std::size_t>(pt)];
1967 const auto& d12_pt = geometry.d12[static_cast<std::size_t>(pt)];
1968 const auto& dn_pt =
1969 shared_distance_neg_per_pt[static_cast<std::size_t>(pt)];
1970 // Substituting:
1971 // D12_pt_actual = -inv_l_pt^2 * geometry.d12[pt]
1972 // D1[n]_actual = +d1_neg
1973 // D2[n]_actual = +d2_neg
1974 // D12[n]_actual = +d12_neg
1975 // D1_pt_actual = -inv_l_pt^2 * geometry.d1[pt]
1976 // D2_pt_actual = -inv_l_pt^2 * geometry.d2[pt]
1977 // dist_pt_actual = -inv_l_pt^2 * dn_pt
1978 //
1979 // DK_pt = K * (inv_l_pt^2 * d12_pt
1980 // - 0.25 * d1_neg * d2_neg * (-inv_l_pt^2 * dn_pt)
1981 // + 0.5 * (d1_neg * (-inv_l_pt^2 * d2_pt)
1982 // + d2_neg * (-inv_l_pt^2 * d1_pt)
1983 // + (-inv_l_pt^2 * dn_pt) * d12_neg))
1984 // = K * (inv_l_pt^2 * d12_pt
1985 // + 0.25 * inv_l_pt^2 * d1_neg * d2_neg * dn_pt
1986 // - 0.5 * inv_l_pt^2 * (d1_neg * d2_pt + d2_neg * d1_pt
1987 // + dn_pt * d12_neg))
1988 // = K * inv_l_pt^2 * (d12_pt
1989 // + 0.25 * d1_neg * d2_neg * dn_pt
1990 // - 0.5 * (d1_neg * d2_pt + d2_neg * d1_pt
1991 // + dn_pt * d12_neg))
1992 DKff[out] = (shared_kernel.array() * inv_length_sq *
1993 (d12_pt.array() +
1994 0.25 * d1_neg.array() * d2_neg.array() * dn_pt.array() -
1995 0.5 * (d1_neg.array() * d2_pt.array() +
1996 d2_neg.array() * d1_pt.array() +
1997 dn_pt.array() * d12_neg.array())))
1998 .matrix();
1999 }
2000 return true;
2001}

◆ calculateGradOfCovMatrixWithDerivativesFromGeometry()

bool gpr::SexpatCF::calculateGradOfCovMatrixWithDerivativesFromGeometry ( const CrossBlockGeometry & geometry,
const FieldMatrixd & shared_kernel,
const std::vector< FieldMatrixd > & shared_distance_neg_per_pt,
const Eigen::VectorXd & theta,
std::vector< FieldMatrixd > & DKff,
const std::vector< Eigen::Index > * parameter_indices = nullptr ) const
nodiscard

Geometry-path replacement for calculateGradOfCovMatrixWithDerivatives (Kdf block dK).

The Kdf block geometry (built once at unit lengthscale and stored in geometry with derivative_options=D1) gives the per-pairtype d1 fields. DKff[0] = Kdf(theta) (== evaluateCrossBlockGeometryWithSharedKernel with options=D1). DKff[1+pt] is dKdf/dloglength_pt; the algebra matches the live calculateGradOfCovMatrixWithDerivatives (DK_pt[pt] = magnSigma2 * exp * (-D1_pt[pt] + 0.5 * D1[n] * dist_pt[pt])) with D1_pt being the per-pairtype gradient at unit lengthscale and D1 being the lengthscale-weighted sum across pairtypes.

Definition at line 1744 of file SexpatCF.cpp.

1749{
1750 const auto fail = [&DKff]() {
1751 DKff.clear();
1752 return false;
1753 };
1754 if (!geometry.valid || theta.size() < 2) return fail();
1755 const auto n_pt =
1756 static_cast<Eigen::Index>(shared_distance_neg_per_pt.size());
1757 const auto n_length_scales = lengthScale.size();
1758 if (n_length_scales <= 0 || theta.size() < 1 + n_length_scales)
1759 return fail();
1760 const bool scalar_length = n_length_scales == 1;
1761 if (!scalar_length && n_length_scales != n_pt) return fail();
1762 if (geometry.d1.size() != static_cast<std::size_t>(n_pt)) return fail();
1763
1764 const Eigen::Index rows = shared_kernel.rows();
1765 const Eigen::Index cols = shared_kernel.cols();
1766 for (Eigen::Index pt = 0; pt < n_pt; ++pt) {
1767 const auto idx = static_cast<std::size_t>(pt);
1768 if (shared_distance_neg_per_pt[idx].rows() != rows ||
1769 shared_distance_neg_per_pt[idx].cols() != cols ||
1770 geometry.d1[idx].rows() != rows ||
1771 geometry.d1[idx].cols() != cols) {
1772 return fail();
1773 }
1774 }
1775 const Eigen::Index parameter_count = scalar_length ? 2 : 1 + n_pt;
1776 if (!valid_gradient_parameter_selection(parameter_indices, parameter_count))
1777 return fail();
1778 const std::size_t n_blocks =
1779 parameter_indices != nullptr
1780 ? parameter_indices->size()
1781 : static_cast<std::size_t>(parameter_count);
1782 if (!resize_geometry_gradient_blocks(DKff, n_blocks, rows, cols)) {
1783 return fail();
1784 }
1785
1786 // Accumulate the per-pairtype per-dim gradient with inv_l_pt^2 weighting,
1787 // matching derivatives.D1[n=0]_actual from calculateDerivativesSameDim
1788 // at the live lengthscale. Note: geometry.d1[pt] = -derivatives_pt.D1[pt]
1789 // at unit lengthscale (negated by buildCrossBlockGeometry /
1790 // DerivativesOnly). So accumulating inv_l_pt^2 * geometry.d1[pt] gives
1791 // -derivatives.D1[0]_actual.
1792 static thread_local FieldMatrixd d1_accum_neg;
1793 if (d1_accum_neg.rows() != rows || d1_accum_neg.cols() != cols)
1794 d1_accum_neg.resize(rows, cols);
1795 d1_accum_neg.setZero();
1796 if (!accumulate_per_pt(geometry.d1, d1_accum_neg, theta, scalar_length,
1797 n_pt)) {
1798 return fail();
1799 }
1800
1801 // DKff[0] = Kdf at theta = ginput4 output
1802 // = -0.5 * K * derivatives.D1[0]_actual
1803 // With evaluateValueInDerivativeField's -= sign convention:
1804 // derivatives_pt.D1[pt]_unit = -sum_{p of pt} deriv_ij_p_unit
1805 // geometry.d1[pt] = -derivatives_pt.D1[pt]_unit = +sum_{p of pt}
1806 // deriv_ij_p_unit derivatives.D1[0]_actual = sum_pt inv_l_pt^2 *
1807 // geometry.d1[pt]
1808 // = d1_accum_neg (positive sum despite name).
1809
1810 // For each pairtype, dKdf/dlog(length_pt) follows the direct formula
1811 // DK_pt = K * (-D1_pt_actual + 0.5 * D1[0]_actual * dist_pt_actual)
1812 // with:
1813 // D1_pt_actual = -inv_l_pt^2 * geometry.d1[pt]
1814 // D1[0]_actual = +d1_accum_neg
1815 // dist_pt_actual = -inv_l_pt^2 * shared_distance_neg_per_pt[pt]
1816 // => DK_pt = K * inv_l_pt^2 * (geometry.d1[pt]
1817 // - 0.5 * d1_accum_neg *
1818 // shared_distance_neg[pt])
1819 for (std::size_t out = 0; out < n_blocks; ++out) {
1820 const Eigen::Index parameter = parameter_indices != nullptr
1821 ? (*parameter_indices)[out]
1822 : static_cast<Eigen::Index>(out);
1823 if (parameter == 0) {
1824 DKff[out] =
1825 (-0.5 * shared_kernel.array() * d1_accum_neg.array()).matrix();
1826 continue;
1827 }
1828 if (scalar_length && n_pt > 1) {
1829 // One shared length varies every pairtype at once.
1830 FieldMatrixd distance = FieldMatrixd::Zero(rows, cols);
1831 for (const auto& part: shared_distance_neg_per_pt)
1832 distance += part;
1833 DKff[out] = (shared_kernel.array() * d1_accum_neg.array() *
1834 (1.0 - 0.5 * numerics::exp(-2.0 * theta(1)) *
1835 distance.array()))
1836 .matrix();
1837 continue;
1838 }
1839 const Eigen::Index pt = parameter - 1;
1840 const double inv_length_sq =
1841 numerics::exp(-2.0 * (scalar_length ? theta(1) : theta(1 + pt)));
1842 const auto& d1_pt = geometry.d1[static_cast<std::size_t>(pt)];
1843 const auto& dn_pt =
1844 shared_distance_neg_per_pt[static_cast<std::size_t>(pt)];
1845 DKff[out] =
1846 (shared_kernel.array() * inv_length_sq *
1847 (d1_pt.array() - 0.5 * d1_accum_neg.array() * dn_pt.array()))
1848 .matrix();
1849 }
1850 return true;
1851}

◆ calculateLogPrior()

double gpr::SexpatCF::calculateLogPrior ( )

Evaluate the log prior density of the parameters.

This function takes a covariance function structure GPCF and returns log(p(th)), where th collects the parameters. This is a mandatory subfunction used for example in energy computations.

Evaluate the prior contribution to the error. The parameters that are sampled are transformed, e.g., W = log(w) where w is all the "real" samples. On the other hand errors are evaluated in the W-space so we need take into account also the Jacobian of transformation, e.g., W -> w = exp(W). See Gelman et al. (2013), Bayesian Data Analysis, third edition, p. 21.

Definition at line 255 of file SexpatCF.cpp.

256{
257 const auto& active_lengths = getLengthScaleRef();
258 // CHEMGP and GPRD_ZBL: original Sexpat prior density from the published
259 // C++ dimer path (gprd_zbl subrepo SexpatCF.cpp).
260 if (usesClassicJointEnergyForcePrior(model_profile_)) {
261 PriorGaussian prior_gaussian;
262 PriorSqrtt prior_sqrtt;
263 FieldMatrixd magn_sigma2(1, 1);
264 magn_sigma2(0, 0) = magnSigma2;
265 prior_gaussian.setParameters(prior_parameters_gaussian);
266 prior_sqrtt.setParameters(prior_parameters_sqrtt);
267
268 double lp = 0.0;
269 if (use_lognormal_magn_prior_ &&
270 prior_parameters_lognormal.getS2() > 0.0) {
271 // Log-normal support is the positive reals. A non-positive
272 // amplitude is rejected; a huge finite one stays finite.
273 if (!(magnSigma2 > 0.0) || !std::isfinite(magnSigma2))
274 return -std::numeric_limits<double>::infinity();
275 PriorLogNormal prior_lognormal;
276 prior_lognormal.setParameters(prior_parameters_lognormal);
277 lp = prior_lognormal.calculateLogPrior(magn_sigma2) +
278 numerics::log(magnSigma2);
279 } else {
280 lp = prior_sqrtt.calculateLogPrior(magn_sigma2) +
281 numerics::log(magnSigma2);
282 }
283 FieldMatrixd one(1, 1);
284 const bool anchors_ready =
285 use_hierarchical_prior_ &&
286 hierarchical_mu_log_.size() == 1 + active_lengths.size();
287 for (Eigen::Index n = 0; n < active_lengths.size(); ++n) {
288 const double length = *(active_lengths.data() + n);
289 const double s2 = hierarchicalPriorVariance(n + 1);
290 if (anchors_ready && hierarchicalAnchored(n) && s2 > 0.0) {
291 // The population's log-Gaussian on this pair type.
292 const double d =
293 numerics::log(length) - hierarchical_mu_log_(n + 1);
294 lp -= lengthPriorWeight(n) * 0.5 *
295 (numerics::log(2.0 * M_PI) + numerics::log(s2) +
296 d * d / s2);
297 continue;
298 }
299 one(0, 0) = length;
300 lp +=
301 lengthPriorWeight(n) *
302 (prior_gaussian.calculateLogPrior(one) + numerics::log(length));
303 }
304 return lp;
305 }
306
307 // Non-hierarchical global GPs use the SCG objective priors as the
308 // single regularisation source: half-Cauchy on sigma_m and
309 // half-Student-t on each lengthscale, annealed by N_eff via
310 // current_barrier_strength. The hierarchical branch is the per-image
311 // GP path and uses this object's packed log-parameter Gaussian prior.
312 if (use_hierarchical_prior_) {
313 // Hierarchical-Bayes Gaussian on the packed *log-space*
314 // parameters: ~theta_log = [log(magnSigma2),
315 // log(active_lengths[0]), ..., log(active_lengths[K-1])] ~ N(mu_log,
316 // s2_log * I)~. The density operates in log-space directly
317 // (the SCG optimiser runs on these packed log-parameters), so
318 // no linear-to-log Jacobian terms are added.
319 const Eigen::Index expected = 1 + active_lengths.size();
320 if (hierarchical_mu_log_.size() != expected) {
321 return 0.0; // shape mismatch: silently no-op the prior term
322 }
323 // Each packed parameter has its own variance (the shared one
324 // unless the population prior set a pair type's width); a
325 // parameter without a positive width carries no term.
326 const double log_2_pi = numerics::log(2.0 * M_PI);
327 double lp = 0.0;
328 const double s2_m = hierarchicalPriorVariance(0);
329 if (s2_m > 0.0) {
330 const double dm =
331 numerics::log(magnSigma2) - hierarchical_mu_log_(0);
332 lp -= 0.5 * (log_2_pi + numerics::log(s2_m)) + 0.5 * dm * dm / s2_m;
333 }
334 for (Eigen::Index n = 0; n < active_lengths.size(); ++n) {
335 const double s2 = hierarchicalPriorVariance(n + 1);
336 if (!(s2 > 0.0)) continue;
337 const double log_ls = numerics::log(*(active_lengths.data() + n));
338 const double dl = log_ls - hierarchical_mu_log_(n + 1);
339 const double weight = lengthPriorWeight(n);
340 lp -= 0.5 * weight * (log_2_pi + numerics::log(s2) + dl * dl / s2);
341 }
342 return lp;
343 }
344
345 // Global GP: Penalized-Complexity length-scale prior, if set. In the packed
346 // log-space parameters (theta = log rho) the PC range prior transforms
347 // (Jacobian drho/dtheta = rho) to
348 // log pi_theta = log(lambda) - log(rho) - lambda/rho.
349 // As rho -> 0 the -lambda/rho term -> -inf, conditioning the optimiser
350 // never to collapse a length scale into a near-singular kernel. magnSigma2
351 // (index 0) is unpenalised.
352 if (use_pc_lengthscale_prior_ &&
353 pc_lambda_.size() == active_lengths.size()) {
354 double lp = 0.0;
355 for (Eigen::Index n = 0; n < active_lengths.size(); ++n) {
356 const double rho = *(active_lengths.data() + n);
357 const double lam = pc_lambda_(n);
358 if (lam > 0.0 && rho > 0.0)
359 lp += lengthPriorWeight(n) *
360 (numerics::log(lam) - numerics::log(rho) - lam / rho);
361 }
362 return lp;
363 }
364 // Otherwise flat; regularisation stays in the SCG barrier terms.
365 // The opt-in log-normal magnitude prior is applied by the MAP
366 // objective on this path, so it is not added a second time here.
367 return 0.0;
368}

◆ calculateLogPriorGradient()

FieldMatrixd gpr::SexpatCF::calculateLogPriorGradient ( )

Evaluate the gradient of the log prior density of the parameters with respect to parameters.

This function takes a covariance function structure GPCF and returns LPG = d log (p(th))/dth, where th is the vector of parameters. This is a mandatory subfunction used in gradient computations.

Definition at line 370 of file SexpatCF.cpp.

371{
372 const auto& active_lengths = getLengthScaleRef();
373 FieldMatrixd lpg;
374 Eigen::Index num_length_scales = active_lengths.size();
375
376 if (usesClassicJointEnergyForcePrior(model_profile_)) {
377 PriorGaussian prior_gaussian;
378 PriorSqrtt prior_sqrtt;
379 FieldMatrixd magn_sigma2(1, 1);
380 magn_sigma2(0, 0) = magnSigma2;
381 prior_gaussian.setParameters(prior_parameters_gaussian);
382 prior_sqrtt.setParameters(prior_parameters_sqrtt);
383
384 lpg.resize(1, 1 + num_length_scales);
385 if (use_lognormal_magn_prior_ &&
386 prior_parameters_lognormal.getS2() > 0.0) {
387 if (!(magnSigma2 > 0.0) || !std::isfinite(magnSigma2)) {
388 lpg(0, 0) = std::numeric_limits<double>::quiet_NaN();
389 } else {
390 const double log_m = numerics::log(magnSigma2);
391 lpg(0, 0) = -(log_m - prior_parameters_lognormal.getMu()) /
392 prior_parameters_lognormal.getS2();
393 }
394 } else {
395 const FieldMatrixd magn_gradient =
396 prior_sqrtt.calculateLogPriorGradient(magn_sigma2);
397 lpg(0, 0) = magn_gradient(0, 0) * magnSigma2 + 1.0;
398 }
399 const FieldMatrixd length_gradient =
400 prior_gaussian.calculateLogPriorGradient(active_lengths);
401 const bool anchors_ready =
402 use_hierarchical_prior_ &&
403 hierarchical_mu_log_.size() == 1 + num_length_scales;
404 for (Eigen::Index n = 0; n < num_length_scales; ++n) {
405 const double length = *(active_lengths.data() + n);
406 const double s2 = hierarchicalPriorVariance(n + 1);
407 if (anchors_ready && hierarchicalAnchored(n) && s2 > 0.0) {
408 lpg(0, 1 + n) =
409 -lengthPriorWeight(n) *
410 (numerics::log(length) - hierarchical_mu_log_(n + 1)) / s2;
411 continue;
412 }
413 lpg(0, 1 + n) = lengthPriorWeight(n) *
414 (*(length_gradient.data() + n) * length + 1.0);
415 }
416 return lpg;
417 }
418
419 if (use_hierarchical_prior_) {
420 // Gradient of the hierarchical Gaussian log-prior wrt the
421 // packed log-parameters: ~d/d(log(theta_j)) [-0.5 (log(theta_j)
422 // - mu_log_j)^2 / s2_log] = -(log(theta_j) - mu_log_j) /
423 // s2_log~. No linear-to-log Jacobian terms because the prior
424 // already lives in log-space; this is the direct gradient that
425 // the SCG optimiser adds to the data NLML gradient.
426 lpg.resize(1, 1 + num_length_scales);
427 const Eigen::Index expected = 1 + num_length_scales;
428 lpg.setZero();
429 if (hierarchical_mu_log_.size() != expected) return lpg;
430 const double s2_m = hierarchicalPriorVariance(0);
431 if (s2_m > 0.0)
432 lpg(0, 0) =
433 -(numerics::log(magnSigma2) - hierarchical_mu_log_(0)) / s2_m;
434 for (Eigen::Index n = 0; n < num_length_scales; ++n) {
435 const double s2 = hierarchicalPriorVariance(n + 1);
436 if (!(s2 > 0.0)) continue;
437 const double log_ls = numerics::log(*(active_lengths.data() + n));
438 lpg(0, 1 + n) = -lengthPriorWeight(n) *
439 (log_ls - hierarchical_mu_log_(n + 1)) / s2;
440 }
441 return lpg;
442 }
443
444 // Global GP gradient mirror. Zero unless the PC length-scale prior is set:
445 // d/dtheta log pi_theta = -1 + lambda/rho per length scale (magnSigma2,
446 // index 0, unpenalised). As rho -> 0 this -> +inf, pushing the optimiser
447 // away from collapse.
448 lpg.resize(1, 1 + num_length_scales);
449 lpg.setZero();
450 if (use_pc_lengthscale_prior_ && pc_lambda_.size() == num_length_scales) {
451 for (Eigen::Index n = 0; n < num_length_scales; ++n) {
452 const double rho = *(active_lengths.data() + n);
453 const double lam = pc_lambda_(n);
454 if (lam > 0.0 && rho > 0.0)
455 lpg(0, 1 + n) = lengthPriorWeight(n) * (-1.0 + lam / rho);
456 }
457 }
458 return lpg;
459}

◆ calculateTrainingCovarianceMatrix()

void gpr::SexpatCF::calculateTrainingCovarianceMatrix ( const Coord & x,
FieldMatrixd & C )

Evaluate the prior variance for each training input.

Function takes in covariance function of a Gaussian process GPCF and matrix TX that contains training inputs. Returns variance vector C. Every element i of C contains variance of input i in TX. This is a mandatory subfunction used for example in prediction and energy computations.

Parameters
xInput configurations whose prior variances are evaluated.
COutput column vector of prior variances, one per configuration.

Definition at line 786 of file SexpatCF.cpp.

788{
789 if (compose_operators_) {
790 if (auto op = assembledOperator()) {
791 C.resize(x.rows(), 1);
792 C.col(0) = op->covarianceBlock(x, x, -1, -1).diagonal();
793 if (usesManifoldChart()) {
794 noteManifoldGeometryRows(x.rows(), x.rows());
795 }
796 return;
797 }
798 }
799 C.resize(x.rows(), 1);
800 if (fabs(magnSigma2) <= DBL_EPSILON)
801 C.setZero();
802 else
803 C.setConstant(magnSigma2);
804}

◆ clear()

void gpr::SexpatCF::clear ( )
inline

Definition at line 68 of file SexpatCF.inl.

69{
71 initialized = false;
72 magnSigma2 = 0.;
73 lengthScale.setConstant(0.);
74 chart_length_scale_.setConstant(0.);
75 conf_info.clearDistribution();
76}
void clearGeodesicHeatKernel() noexcept
Definition SexpatCF.cpp:723

◆ clearDistanceCache()

void gpr::SexpatCF::clearDistanceCache ( )

Invalidate the distance cache.

Call when positions change (e.g. after optimization completes and new observations are added).

Definition at line 2963 of file SexpatCF.cpp.

2964{
2965 dist_calculator_.clearCache();
2966}

◆ clearGeodesicHeatKernel()

void gpr::SexpatCF::clearGeodesicHeatKernel ( )
noexcept

Definition at line 723 of file SexpatCF.cpp.

724{
725 geodesic_heat_kernel_.reset();
727}
void clearDistanceCache()
Invalidate the distance cache.

◆ clearHierarchicalPrior()

void gpr::SexpatCF::clearHierarchicalPrior ( )
inline

Disable the hierarchical prior set via ~setHierarchicalPrior~. Restores the global-GP zero-prior branch.

Definition at line 152 of file SexpatCF.inl.

153{
154 use_hierarchical_prior_ = false;
155 hierarchical_mu_log_.resize(0);
156 hierarchical_s2_log_ = 0.0;
157 hierarchical_s2_log_per_.resize(0);
158 hierarchical_anchor_.clear();
159}

◆ clearManifoldChart()

void gpr::SexpatCF::clearManifoldChart ( )

Definition at line 513 of file SexpatCF.cpp.

514{
515 manifold_chart_.reset();
517}

◆ clearPcLengthScalePrior()

void gpr::SexpatCF::clearPcLengthScalePrior ( )
inline

Definition at line 167 of file SexpatCF.inl.

168{
169 use_pc_lengthscale_prior_ = false;
170 pc_lambda_.resize(0);
171}

◆ combineParameters()

Eigen::VectorXd gpr::SexpatCF::combineParameters ( )
inline

Combine parameters of the covariance function into one Eigen vector.

Definition at line 173 of file SexpatCF.inl.

174{
175 const auto& lengths = getLengthScaleRef();
176 Eigen::VectorXd res(1 + lengths.size());
177
178 res(0) = numerics::log(magnSigma2);
179
180 for (Eigen::Index n = 0; n < lengths.size(); ++n)
181 res(n + 1) = numerics::log(*(lengths.data() + n));
182
183 // NOTE: Only magnSigma2 and lengths are packed, matching MATLAB
184 // gpcf_sexpat_pak. Prior parameters are not part of the optimization
185 // vector.
186 return res;
187}

◆ correlationDistances()

void gpr::SexpatCF::correlationDistances ( const Coord & left,
const Coord & right,
const AtomsConfiguration & configuration,
FieldMatrixd & distances ) const

Dimensionless support scores from the selected prediction covariance. A score of one corresponds to normalized energy covariance exp(-1/2). Nonpositive composed covariance gives an infinite score.

Definition at line 2921 of file SexpatCF.cpp.

2924{
2925 if (usesGeodesicHeatKernel()) {
2926 distances =
2927 assembledOperator()->energyCorrelationDistances(left, right);
2928 return;
2929 }
2930 if (!usesManifoldChart()) {
2931 aux::Distance metric;
2932 metric.setFarFieldRadius(far_field_radius_);
2933 metric.dist_at(left, right, configuration, lengthScale, distances);
2934 return;
2935 }
2936
2937 distances.resize(left.rows(), right.rows());
2938 distances.setConstant(std::numeric_limits<double>::infinity());
2939 if (left.cols() != manifoldDimensions() ||
2940 right.cols() != manifoldDimensions() || !left.allFinite() ||
2941 !right.allFinite() || chart_length_scale_.size() != 1) {
2942 return;
2943 }
2944 const double scale = chart_length_scale_(0, 0);
2945 if (!(scale > 0.0) || !std::isfinite(scale)) return;
2946
2947 Eigen::MatrixXd right_coordinates(right.rows(), manifold_chart_->rank());
2948 for (Eigen::Index j = 0; j < right.rows(); ++j) {
2949 right_coordinates.row(j) =
2950 manifold_chart_->coordinates(right.row(j).transpose()).transpose();
2951 }
2952 for (Eigen::Index i = 0; i < left.rows(); ++i) {
2953 const Eigen::VectorXd coordinate =
2954 manifold_chart_->coordinates(left.row(i).transpose());
2955 for (Eigen::Index j = 0; j < right.rows(); ++j) {
2956 distances(i, j) =
2957 (coordinate - right_coordinates.row(j).transpose()).norm() /
2958 scale;
2959 }
2960 }
2961}
void dist_at(const gpr::Coord &x1, const gpr::Coord &x2, const gpr::AtomsConfiguration &conf_info, const gpr::FieldMatrixd &lengthscale, gpr::FieldMatrixd &dist, bool take_sqrt=true)
Give the distance between two atomic configurations as defined in the special GPstuff covariance func...
Definition Distance.cpp:620
Eigen::Index manifoldDimensions() const noexcept
Definition SexpatCF.h:626

◆ evaluateCrossBlockGeometry()

bool gpr::SexpatCF::evaluateCrossBlockGeometry ( const CrossBlockGeometry & geometry,
const Eigen::VectorXd & theta,
FieldMatrixd & out ) const
nodiscard

Evaluate a cross-block geometry at packed Sexpat log parameters.

Definition at line 1018 of file SexpatCF.cpp.

1021{
1022 auto fail = [&out]() {
1023 out.resize(0, 0);
1024 return false;
1025 };
1026 if (!geometry.valid || geometry.distance.empty() || theta.size() < 2) {
1027 return fail();
1028 }
1029
1030 const auto n_pairtypes =
1031 static_cast<Eigen::Index>(geometry.distance.size());
1032 const auto n_length_scales = lengthScale.size();
1033 if (n_length_scales <= 0 || theta.size() < 1 + n_length_scales) {
1034 return fail();
1035 }
1036 const bool scalar_length = n_length_scales == 1;
1037 if (!scalar_length && n_length_scales != n_pairtypes) {
1038 return fail();
1039 }
1040
1041 const Eigen::Index rows = geometry.distance[0].rows();
1042 const Eigen::Index cols = geometry.distance[0].cols();
1043 if (scalar_length && n_pairtypes == 1) {
1044 const auto& q = geometry.distance[0];
1045 if (q.rows() != rows || q.cols() != cols) return false;
1046 const double inv_length_sq = numerics::exp(-2.0 * theta(1));
1047 out =
1048 (numerics::exp(theta(0)) * (-0.5 * inv_length_sq * q.array()).exp())
1049 .matrix();
1050 switch (geometry.derivative_options) {
1051 case 0:
1052 return true;
1054 if (geometry.d1.size() != 1 || geometry.d1[0].rows() != rows ||
1055 geometry.d1[0].cols() != cols) {
1056 return false;
1057 }
1058 out.array() *= -0.5 * inv_length_sq * geometry.d1[0].array();
1059 return true;
1062 if (geometry.d1.size() != 1 || geometry.d2.size() != 1 ||
1063 geometry.d12.size() != 1 || geometry.d1[0].rows() != rows ||
1064 geometry.d1[0].cols() != cols ||
1065 geometry.d2[0].rows() != rows ||
1066 geometry.d2[0].cols() != cols ||
1067 geometry.d12[0].rows() != rows ||
1068 geometry.d12[0].cols() != cols) {
1069 return false;
1070 }
1071 out.array() *=
1072 (-0.5 * inv_length_sq * geometry.d12[0].array() +
1073 0.25 * inv_length_sq * inv_length_sq *
1074 geometry.d1[0].array() * geometry.d2[0].array());
1075 return true;
1076 }
1077 return false;
1078 }
1079
1080 FieldMatrixd q = FieldMatrixd::Zero(rows, cols);
1081 FieldMatrixd d1;
1082 FieldMatrixd d2;
1083 FieldMatrixd d12;
1084 const bool need_d1 = geometry.derivative_options != 0;
1085 const bool need_d2d12 =
1086 geometry.derivative_options ==
1089 if (need_d1) d1 = FieldMatrixd::Zero(rows, cols);
1090 if (need_d2d12) {
1091 d2 = FieldMatrixd::Zero(rows, cols);
1092 d12 = FieldMatrixd::Zero(rows, cols);
1093 }
1094
1095 auto add_scaled_fields = [&](const std::vector<FieldMatrixd>& fields,
1096 FieldMatrixd& target, Eigen::Index pt,
1097 double scale) -> bool {
1098 if (fields.empty()) return true;
1099 if (pt >= static_cast<Eigen::Index>(fields.size())) return false;
1100 if (fields[static_cast<std::size_t>(pt)].rows() != rows ||
1101 fields[static_cast<std::size_t>(pt)].cols() != cols) {
1102 return false;
1103 }
1104 target.noalias() += scale * fields[static_cast<std::size_t>(pt)];
1105 return true;
1106 };
1107
1108 for (Eigen::Index pt = 0; pt < n_pairtypes; ++pt) {
1109 if (geometry.distance[static_cast<std::size_t>(pt)].rows() != rows ||
1110 geometry.distance[static_cast<std::size_t>(pt)].cols() != cols) {
1111 return false;
1112 }
1113 const double log_length = scalar_length ? theta(1) : theta(1 + pt);
1114 const double inv_length_sq = numerics::exp(-2.0 * log_length);
1115 q.noalias() +=
1116 inv_length_sq * geometry.distance[static_cast<std::size_t>(pt)];
1117 if (need_d1 && !add_scaled_fields(geometry.d1, d1, pt, inv_length_sq)) {
1118 return false;
1119 }
1120 if (need_d2d12 &&
1121 (!add_scaled_fields(geometry.d2, d2, pt, inv_length_sq) ||
1122 !add_scaled_fields(geometry.d12, d12, pt, inv_length_sq))) {
1123 return false;
1124 }
1125 }
1126
1127 out = (numerics::exp(theta(0)) * (-0.5 * q.array()).exp()).matrix();
1128 switch (geometry.derivative_options) {
1129 case 0:
1130 return true;
1132 if (geometry.d1.empty()) return false;
1133 out.array() *= -0.5 * d1.array();
1134 return true;
1137 if (geometry.d1.empty() || geometry.d2.empty() ||
1138 geometry.d12.empty()) {
1139 return false;
1140 }
1141 out.array() *=
1142 (-0.5 * d12.array() + 0.25 * d1.array() * d2.array());
1143 return true;
1144 }
1145 return false;
1146}

◆ evaluateCrossBlockGeometryShared()

bool gpr::SexpatCF::evaluateCrossBlockGeometryShared ( const CrossBlockGeometry & geometry,
const std::vector< FieldMatrixd > & shared_distance_neg_per_pt,
const Eigen::VectorXd & theta,
FieldMatrixd & out ) const
nodiscard

Same as evaluateCrossBlockGeometry but reads the per-pairtype distance from an externally-shared tensor (negated, matching the sign convention of buildCrossBlockGeometry). The supplied geometry's .distance field is ignored; .d1, .d2, .d12 are still consulted.

Used together with buildCrossBlockDerivativesOnly to skip 946-fold redundant dist_at_vec calls in the SCG training-cov assembly when all (block_n, block_m) blocks share the same atom positions.

Definition at line 1148 of file SexpatCF.cpp.

1152{
1153 auto fail = [&out]() {
1154 out.resize(0, 0);
1155 return false;
1156 };
1157 if (!geometry.valid || theta.size() < 2) return fail();
1158 const auto n_pairtypes =
1159 static_cast<Eigen::Index>(shared_distance_neg_per_pt.size());
1160 const auto n_length_scales = lengthScale.size();
1161 if (n_pairtypes <= 0 || n_length_scales <= 0 ||
1162 theta.size() < 1 + n_length_scales) {
1163 return fail();
1164 }
1165 const bool scalar_length = n_length_scales == 1;
1166 if (!scalar_length && n_length_scales != n_pairtypes) return fail();
1167
1168 const Eigen::Index rows = shared_distance_neg_per_pt[0].rows();
1169 const Eigen::Index cols = shared_distance_neg_per_pt[0].cols();
1170
1171 if (scalar_length && n_pairtypes == 1) {
1172 const auto& q = shared_distance_neg_per_pt[0];
1173 if (q.rows() != rows || q.cols() != cols) return false;
1174 const double inv_length_sq = numerics::exp(-2.0 * theta(1));
1175 out =
1176 (numerics::exp(theta(0)) * (-0.5 * inv_length_sq * q.array()).exp())
1177 .matrix();
1178 switch (geometry.derivative_options) {
1179 case 0:
1180 return true;
1182 if (geometry.d1.size() != 1 || geometry.d1[0].rows() != rows ||
1183 geometry.d1[0].cols() != cols) {
1184 return false;
1185 }
1186 out.array() *= -0.5 * inv_length_sq * geometry.d1[0].array();
1187 return true;
1190 if (geometry.d1.size() != 1 || geometry.d2.size() != 1 ||
1191 geometry.d12.size() != 1 || geometry.d1[0].rows() != rows ||
1192 geometry.d1[0].cols() != cols ||
1193 geometry.d2[0].rows() != rows ||
1194 geometry.d2[0].cols() != cols ||
1195 geometry.d12[0].rows() != rows ||
1196 geometry.d12[0].cols() != cols) {
1197 return false;
1198 }
1199 out.array() *=
1200 (-0.5 * inv_length_sq * geometry.d12[0].array() +
1201 0.25 * inv_length_sq * inv_length_sq *
1202 geometry.d1[0].array() * geometry.d2[0].array());
1203 return true;
1204 }
1205 return false;
1206 }
1207
1208 FieldMatrixd q = FieldMatrixd::Zero(rows, cols);
1209 FieldMatrixd d1;
1210 FieldMatrixd d2;
1211 FieldMatrixd d12;
1212 const bool need_d1 = geometry.derivative_options != 0;
1213 const bool need_d2d12 =
1214 geometry.derivative_options ==
1217 if (need_d1) d1 = FieldMatrixd::Zero(rows, cols);
1218 if (need_d2d12) {
1219 d2 = FieldMatrixd::Zero(rows, cols);
1220 d12 = FieldMatrixd::Zero(rows, cols);
1221 }
1222
1223 auto add_scaled_fields = [&](const std::vector<FieldMatrixd>& fields,
1224 FieldMatrixd& target, Eigen::Index pt,
1225 double scale) -> bool {
1226 if (fields.empty()) return true;
1227 if (pt >= static_cast<Eigen::Index>(fields.size())) return false;
1228 if (fields[static_cast<std::size_t>(pt)].rows() != rows ||
1229 fields[static_cast<std::size_t>(pt)].cols() != cols) {
1230 return false;
1231 }
1232 target.noalias() += scale * fields[static_cast<std::size_t>(pt)];
1233 return true;
1234 };
1235
1236 for (Eigen::Index pt = 0; pt < n_pairtypes; ++pt) {
1237 if (shared_distance_neg_per_pt[static_cast<std::size_t>(pt)].rows() !=
1238 rows ||
1239 shared_distance_neg_per_pt[static_cast<std::size_t>(pt)].cols() !=
1240 cols) {
1241 return false;
1242 }
1243 const double log_length = scalar_length ? theta(1) : theta(1 + pt);
1244 const double inv_length_sq = numerics::exp(-2.0 * log_length);
1245 q.noalias() += inv_length_sq *
1246 shared_distance_neg_per_pt[static_cast<std::size_t>(pt)];
1247 if (need_d1 && !add_scaled_fields(geometry.d1, d1, pt, inv_length_sq)) {
1248 return false;
1249 }
1250 if (need_d2d12 &&
1251 (!add_scaled_fields(geometry.d2, d2, pt, inv_length_sq) ||
1252 !add_scaled_fields(geometry.d12, d12, pt, inv_length_sq))) {
1253 return false;
1254 }
1255 }
1256
1257 out = (numerics::exp(theta(0)) * (-0.5 * q.array()).exp()).matrix();
1258 switch (geometry.derivative_options) {
1259 case 0:
1260 return true;
1262 if (geometry.d1.empty()) return false;
1263 out.array() *= -0.5 * d1.array();
1264 return true;
1267 if (geometry.d1.empty() || geometry.d2.empty() ||
1268 geometry.d12.empty()) {
1269 return false;
1270 }
1271 out.array() *=
1272 (-0.5 * d12.array() + 0.25 * d1.array() * d2.array());
1273 return true;
1274 }
1275 return false;
1276}

◆ evaluateCrossBlockGeometryWithSharedKernel()

bool gpr::SexpatCF::evaluateCrossBlockGeometryWithSharedKernel ( const CrossBlockGeometry & geometry,
const FieldMatrixd & shared_kernel,
const Eigen::VectorXd & theta,
FieldMatrixd & out ) const
nodiscard

Evaluate a derivative-only block against a pre-computed shared kernel matrix (from buildSharedKernel). No exp() per call.

Definition at line 1345 of file SexpatCF.cpp.

1348{
1349 auto fail = [&out]() {
1350 out.resize(0, 0);
1351 return false;
1352 };
1353 if (!geometry.valid || theta.size() < 2) return fail();
1354 const auto n_length_scales = lengthScale.size();
1355 if (n_length_scales <= 0 || theta.size() < 1 + n_length_scales)
1356 return fail();
1357 const bool scalar_length = n_length_scales == 1;
1358
1359 if (geometry.derivative_options == 0) {
1360 // Kff is the shared kernel. Force blocks use the same untruncated
1361 // k so cov(E, dE) stays d/dx' k (Rasmussen-Williams 9.4).
1362 if (out.rows() != shared_kernel.rows() ||
1363 out.cols() != shared_kernel.cols()) {
1364 out.resize(shared_kernel.rows(), shared_kernel.cols());
1365 }
1366 out.noalias() = shared_kernel;
1367 return true;
1368 }
1369
1370 const Eigen::Index rows = shared_kernel.rows();
1371 const Eigen::Index cols = shared_kernel.cols();
1372
1373 // The derivative blocks need per-pairtype inv_length_sq weighting on the
1374 // d1/d2/d12 fields. Accumulate then apply against the shared kernel.
1375 FieldMatrixd d1;
1376 FieldMatrixd d2;
1377 FieldMatrixd d12;
1378 const bool need_d1 = geometry.derivative_options != 0;
1379 const bool need_d2d12 =
1380 geometry.derivative_options ==
1383 if (need_d1) d1 = FieldMatrixd::Zero(rows, cols);
1384 if (need_d2d12) {
1385 d2 = FieldMatrixd::Zero(rows, cols);
1386 d12 = FieldMatrixd::Zero(rows, cols);
1387 }
1388 const auto n_pairtypes_d1 = static_cast<Eigen::Index>(geometry.d1.size());
1389 const auto n_pairtypes_d12 = static_cast<Eigen::Index>(geometry.d12.size());
1390 const auto n_pairtypes =
1391 std::max<Eigen::Index>(n_pairtypes_d1, n_pairtypes_d12);
1392 auto add = [&](const std::vector<FieldMatrixd>& src, FieldMatrixd& dst,
1393 Eigen::Index pt, double scale) -> bool {
1394 if (src.empty()) return true;
1395 if (pt >= static_cast<Eigen::Index>(src.size())) return false;
1396 if (src[static_cast<std::size_t>(pt)].rows() != rows ||
1397 src[static_cast<std::size_t>(pt)].cols() != cols) {
1398 return false;
1399 }
1400 dst.noalias() += scale * src[static_cast<std::size_t>(pt)];
1401 return true;
1402 };
1403 for (Eigen::Index pt = 0; pt < n_pairtypes; ++pt) {
1404 const double log_length = scalar_length ? theta(1) : theta(1 + pt);
1405 const double inv_length_sq = numerics::exp(-2.0 * log_length);
1406 if (need_d1 && !add(geometry.d1, d1, pt, inv_length_sq)) {
1407 return false;
1408 }
1409 if (need_d2d12 && (!add(geometry.d2, d2, pt, inv_length_sq) ||
1410 !add(geometry.d12, d12, pt, inv_length_sq))) {
1411 return false;
1412 }
1413 }
1414
1415 switch (geometry.derivative_options) {
1417 if (geometry.d1.empty()) return false;
1418 // Kdf: -0.5 * (sum_pt inv_l^2 * d1[pt]) * kernel (the
1419 // -0.5*inv_l^2 factor is already inside d1 via the accumulate).
1420 out = shared_kernel;
1421 out.array() *= -0.5 * d1.array();
1422 return true;
1425 if (geometry.d1.empty() || geometry.d2.empty() ||
1426 geometry.d12.empty()) {
1427 return false;
1428 }
1429 out = shared_kernel;
1430 out.array() *=
1431 (-0.5 * d12.array() + 0.25 * d1.array() * d2.array());
1432 return true;
1433 }
1434 return false;
1435}

◆ farFieldRadius()

double gpr::SexpatCF::farFieldRadius ( ) const
inlinenodiscard

Definition at line 605 of file SexpatCF.h.

606 {
607 return far_field_radius_;
608 }

◆ geodesicHeatDimensions()

Eigen::Index gpr::SexpatCF::geodesicHeatDimensions ( ) const
inlinenodiscardnoexcept

Definition at line 668 of file SexpatCF.h.

669 {
670 return geodesic_heat_kernel_ ? geodesic_heat_kernel_->dimensions() : 0;
671 }

◆ geodesicHeatJointEnergyGradientCovariance()

FieldMatrixd gpr::SexpatCF::geodesicHeatJointEnergyGradientCovariance ( const Coord & positions) const
nodiscard

Definition at line 729 of file SexpatCF.cpp.

731{
732 if (!geodesic_heat_kernel_) {
733 throw std::logic_error(
734 "Sexpat geodesic heat covariance is not configured");
735 }
736 return GeodesicHeat(geodesic_heat_kernel_)
737 .jointEnergyGradientCovariance(positions);
738}

◆ geodesicHeatJointEnergyGradientCrossCovariance()

FieldMatrixd gpr::SexpatCF::geodesicHeatJointEnergyGradientCrossCovariance ( const Coord & left_positions,
const Coord & right_positions ) const
nodiscard

Definition at line 740 of file SexpatCF.cpp.

742{
743 if (!geodesic_heat_kernel_) {
744 throw std::logic_error(
745 "Sexpat geodesic heat covariance is not configured");
746 }
747 return GeodesicHeat(geodesic_heat_kernel_)
748 .jointEnergyGradientCrossCovariance(left_positions, right_positions);
749}

◆ geodesicHeatKernel()

const std::shared_ptr< const GeodesicHeatEnergyForceKernel > & gpr::SexpatCF::geodesicHeatKernel ( ) const
inlinenodiscardnoexcept

Definition at line 657 of file SexpatCF.h.

658 {
659 return geodesic_heat_kernel_;
660 }

◆ getAtomisticLengthScaleRef() [1/2]

const FieldMatrixd & gpr::SexpatCF::getAtomisticLengthScaleRef ( ) const
inlinenodiscardnoexcept

Definition at line 705 of file SexpatCF.h.

707 {
708 return lengthScale;
709 }

◆ getAtomisticLengthScaleRef() [2/2]

FieldMatrixd & gpr::SexpatCF::getAtomisticLengthScaleRef ( )
inlinenodiscardnoexcept

Pair-type metric retained independently of the chart's fitted length.

Definition at line 700 of file SexpatCF.h.

701 {
702 return lengthScale;
703 }

◆ getConfInfo()

const AtomsConfiguration & gpr::SexpatCF::getConfInfo ( ) const
inlinenodiscardnoexcept

Definition at line 678 of file SexpatCF.h.

679 {
680 return conf_info;
681 }

◆ getLengthScaleRef() [1/2]

FieldMatrixd & gpr::SexpatCF::getLengthScaleRef ( )
inline

Definition at line 58 of file SexpatCF.inl.

59{
60 return usesManifoldChart() ? chart_length_scale_ : lengthScale;
61}

◆ getLengthScaleRef() [2/2]

const FieldMatrixd & gpr::SexpatCF::getLengthScaleRef ( ) const
inline

Definition at line 63 of file SexpatCF.inl.

64{
65 return usesManifoldChart() ? chart_length_scale_ : lengthScale;
66}

◆ getMagnSigma2() [1/2]

double gpr::SexpatCF::getMagnSigma2 ( )
inline

Definition at line 53 of file SexpatCF.inl.

54{
55 return magnSigma2;
56}

◆ getMagnSigma2() [2/2]

double gpr::SexpatCF::getMagnSigma2 ( ) const
inline

Definition at line 692 of file SexpatCF.h.

693 {
694 return magnSigma2;
695 }

◆ getModelProfile()

GPModelProfile gpr::SexpatCF::getModelProfile ( ) const
inlinenodiscardnoexcept

Definition at line 739 of file SexpatCF.h.

740 {
741 return model_profile_;
742 }

◆ getPriorParametersGaussian()

PriorBase gpr::SexpatCF::getPriorParametersGaussian ( )
inline

Definition at line 93 of file SexpatCF.inl.

94{
95 return prior_parameters_gaussian;
96}

◆ getPriorParametersLogNormal()

PriorBase gpr::SexpatCF::getPriorParametersLogNormal ( )
inline

Definition at line 103 of file SexpatCF.inl.

104{
105 return prior_parameters_lognormal;
106}

◆ getPriorParametersSqrtt()

PriorBase gpr::SexpatCF::getPriorParametersSqrtt ( )
inline

Definition at line 98 of file SexpatCF.inl.

99{
100 return prior_parameters_sqrtt;
101}

◆ ginput2()

void gpr::SexpatCF::ginput2 ( const Coord & x1,
Coord & x2,
FieldMatrixIdx & dims,
std::vector< FieldMatrixd > & DKff,
ExpDistArray * out_expdist = nullptr )

Definition at line 2650 of file SexpatCF.cpp.

2653{
2654 if (compose_operators_ && usesManifoldChart()) {
2655 if (x2.size() == 0) x2 = x1;
2656 const auto op = assembledOperator();
2657 DKff.clear();
2658 DKff.reserve(static_cast<std::size_t>(dims.size()));
2659 for (Eigen::Index n = 0; n < dims.size(); ++n) {
2660 const Eigen::Index channel = dims(n) - 1;
2661 noteManifoldGeometryRows(x1.rows(), x2.rows());
2662 DKff.push_back(op->covarianceBlock(x1, x2, channel, channel));
2663 }
2664 return;
2665 }
2666 // thread_local assembly scratch: reuses the gradient-block temporaries
2667 // across the many ginput calls per outer (per SCG NLML eval and per
2668 // inner-loop predict). The Derivatives vectors are cleared at entry so
2669 // calculateDerivatives* push_backs reuse vector capacity; the
2670 // FieldMatrixd temporaries are fully overwritten before use. Value-
2671 // identical (pure allocation reuse). thread_local keeps scratch private
2672 // per thread under the OpenMP serial-oracle region.
2673 thread_local aux::Gradient grad_calculator;
2674 grad_calculator.setFarFieldRadius(far_field_radius_);
2675 thread_local FieldMatrixd dist;
2676 thread_local Derivatives<std::vector<FieldMatrixd>> derivatives;
2677 thread_local Derivatives<std::vector<FieldMatrixd>> derivatives_pt;
2678 thread_local FieldMatrixd DK;
2679 // derivatives.* are reserve+push_back'd per dimension, so they must start
2680 // empty. derivatives_pt.* are sized and zeroed in full by
2681 // resizeDerivativeFields, so clearing them here only throws away storage
2682 // that the next call reallocates.
2683 derivatives.D1.clear();
2684 derivatives.D2.clear();
2685 derivatives.D12.clear();
2686 uint8_t calc_options = OptionsForGradCalculation::D1 |
2689
2690 DKff.clear();
2691
2692 dist_calculator_.dist_at_cached_sq(x1, x2, conf_info, lengthScale, dist);
2693
2694 grad_calculator.calculateDerivativesSameDim(x1, x2, conf_info, lengthScale,
2695 dims, calc_options, derivatives,
2696 derivatives_pt);
2697
2698 // dist already stores squared distances here. thread_local exp buffer
2699 // reused across calls (RowMajor matches dist's storage).
2700 thread_local Eigen::Array<double, Eigen::Dynamic, Eigen::Dynamic,
2701 Eigen::RowMajor>
2702 expdist;
2703 expdist = (-0.5 * dist.array()).exp();
2704 // Hand the factor to a caller that needs the same exp over the same
2705 // distances, so it is evaluated once per call rather than twice.
2706 if (out_expdist != nullptr) *out_expdist = expdist;
2707
2708 for (Eigen::Index n = 0; n < dims.size(); ++n) {
2709 DK = (magnSigma2 * expdist *
2710 (-0.5 * derivatives.D12[n].array() +
2711 0.25 * derivatives.D1[n].array() * derivatives.D2[n].array()))
2712 .matrix();
2713 if (compose_operators_ && usesGeodesicHeatKernel()) {
2714 const Eigen::Index channel = dims(n) - 1;
2715 DK += GeodesicHeat(geodesic_heat_kernel_)
2716 .covarianceBlock(x1, x2, channel, channel);
2717 }
2718 DKff.push_back(std::move(DK));
2719 }
2720}

◆ ginput3()

void gpr::SexpatCF::ginput3 ( const Coord & x1,
Coord & x2,
FieldMatrixIdx & dims1,
FieldMatrixIdx & dims2,
std::vector< FieldMatrixd > & DKff,
ExpDistArray * out_expdist = nullptr,
const SharedDerivatives * precomputed = nullptr )

Definition at line 2722 of file SexpatCF.cpp.

2726{
2727 if (compose_operators_ && usesManifoldChart()) {
2728 if (x2.size() == 0) x2 = x1;
2729 const auto op = assembledOperator();
2730 DKff.clear();
2731 DKff.reserve(static_cast<std::size_t>(dims1.size() * dims2.size()));
2732 for (Eigen::Index i = 0; i < dims1.size(); ++i) {
2733 for (Eigen::Index j = 0; j < dims2.size(); ++j) {
2734 noteManifoldGeometryRows(x1.rows(), x2.rows());
2735 DKff.push_back(
2736 op->covarianceBlock(x1, x2, dims1(i) - 1, dims2(j) - 1));
2737 }
2738 }
2739 return;
2740 }
2741 // thread_local assembly scratch: see ginput2 above for the value-
2742 // identity argument. Cleared at entry so vector capacity is reused.
2743 thread_local aux::Gradient grad_calculator;
2744 grad_calculator.setFarFieldRadius(far_field_radius_);
2745 thread_local FieldMatrixd dist;
2746 thread_local Derivatives<std::vector<FieldMatrixd>> derivatives;
2747 thread_local Derivatives<std::vector<FieldMatrixd>> derivatives_pt;
2748 thread_local FieldMatrixd DK;
2749 // derivatives.* are reserve+push_back'd per dimension, so they must start
2750 // empty. derivatives_pt.* are sized and zeroed in full by
2751 // resizeDerivativeFields, so clearing them here only throws away storage
2752 // that the next call reallocates.
2753 derivatives.D1.clear();
2754 derivatives.D2.clear();
2755 derivatives.D12.clear();
2756 uint8_t calc_options = OptionsForGradCalculation::D1 |
2759
2760 DKff.clear();
2761
2762 dist_calculator_.dist_at_cached_sq(x1, x2, conf_info, lengthScale, dist);
2763
2764 // The caller may already hold these: it asks for D1|D2|D12 plus the _pt
2765 // fields over the same inputs, and Gradient.cpp never reads the direction
2766 // argument that appears to distinguish the two requests, so the D1/D2/D12
2767 // it gets back are the same values this call would produce.
2768 const SharedDerivatives* active = precomputed;
2769 if (active == nullptr) {
2770 grad_calculator.calculateDerivativesDiffDim(
2771 x1, x2, conf_info, lengthScale, dims1, dims2, calc_options,
2772 Directions::y, derivatives, derivatives_pt);
2773 active = &derivatives;
2774 }
2775
2776 // dist already stores squared distances here. thread_local exp buffer
2777 // reused across calls instead of a fresh per-call eval() temporary;
2778 // RowMajor matches dist's storage so the assignment is a plain copy.
2779 thread_local Eigen::Array<double, Eigen::Dynamic, Eigen::Dynamic,
2780 Eigen::RowMajor>
2781 expdist;
2782 expdist = (-0.5 * dist.array()).exp();
2783 // Hand the factor to a caller that needs the same exp over the same
2784 // distances, so it is evaluated once per call rather than twice.
2785 if (out_expdist != nullptr) *out_expdist = expdist;
2786
2787 Index_t n = 0;
2788 for (Eigen::Index i = 0; i < dims1.size(); ++i) {
2789 for (Eigen::Index j = 0; j < dims2.size(); ++j) {
2790 DK = (magnSigma2 * expdist *
2791 (-0.5 * active->D12[n].array() +
2792 0.25 * active->D1[n].array() * active->D2[n].array()))
2793 .matrix();
2794 if (compose_operators_ && usesGeodesicHeatKernel()) {
2795 DK += GeodesicHeat(geodesic_heat_kernel_)
2796 .covarianceBlock(x1, x2, dims1(i) - 1, dims2(j) - 1);
2797 }
2798 DKff.push_back(std::move(DK));
2799 ++n;
2800 }
2801 }
2802}
Derivatives< std::vector< FieldMatrixd > > SharedDerivatives
Evaluate gradient of covariance function with respect to both input variables x1 and x2 (in different...
Definition SexpatCF.h:502

◆ ginput4()

void gpr::SexpatCF::ginput4 ( const Coord & x1,
Coord & x2,
FieldMatrixIdx & dims,
std::vector< FieldMatrixd > & DKff,
ExpDistArray * out_expdist = nullptr )

Evaluate gradient of covariance function with respect to x.

Simplified and faster version of sexp_ginput, returns full matrices.

Returns DKff, the gradients of covariance matrix Kff = k(X,X2) with respect to dimensions DIMS of X.

Parameters
x1Configurations supplying the first covariance argument.
x2Configurations supplying the second covariance argument.
dimsCoordinate-dimension indices differentiated in x1.
DKffOutput covariance-derivative blocks.
out_expdistOptional output array of the shared exponential distance factors.

Definition at line 2804 of file SexpatCF.cpp.

2807{
2808 if (compose_operators_ && usesManifoldChart()) {
2809 if (x2.size() == 0) x2 = x1;
2810 const auto op = assembledOperator();
2811 DKff.clear();
2812 DKff.reserve(static_cast<std::size_t>(dims.size()));
2813 for (Eigen::Index n = 0; n < dims.size(); ++n) {
2814 noteManifoldGeometryRows(x1.rows(), x2.rows());
2815 DKff.push_back(op->covarianceBlock(x1, x2, dims(n) - 1, -1));
2816 }
2817 return;
2818 }
2819 // thread_local assembly scratch: see ginput2 above for the value-
2820 // identity argument. Cleared at entry so vector capacity is reused.
2821 thread_local aux::Gradient grad_calculator;
2822 grad_calculator.setFarFieldRadius(far_field_radius_);
2823 thread_local FieldMatrixd dist;
2824 thread_local Derivatives<std::vector<FieldMatrixd>> derivatives;
2825 thread_local Derivatives<std::vector<FieldMatrixd>> derivatives_pt;
2826 thread_local FieldMatrixd DK;
2827 // derivatives.* are reserve+push_back'd per dimension, so they must start
2828 // empty. derivatives_pt.* are sized and zeroed in full by
2829 // resizeDerivativeFields, so clearing them here only throws away storage
2830 // that the next call reallocates.
2831 derivatives.D1.clear();
2832 derivatives.D2.clear();
2833 derivatives.D12.clear();
2834 uint8_t calc_options = OptionsForGradCalculation::D1;
2835
2836 DKff.clear();
2837
2838 if (x2.size() == 0) x2 = x1;
2839
2840 dist_calculator_.dist_at_cached_sq(x1, x2, conf_info, lengthScale, dist);
2841
2842 grad_calculator.calculateDerivativesSameDim(x1, x2, conf_info, lengthScale,
2843 dims, calc_options, derivatives,
2844 derivatives_pt);
2845
2846 // Pre-compute the common exponential factor. thread_local buffer reused
2847 // across calls (RowMajor matches dist's storage).
2848 thread_local Eigen::Array<double, Eigen::Dynamic, Eigen::Dynamic,
2849 Eigen::RowMajor>
2850 exp_factor;
2851 // Materialise the bare exp first so a caller can take it instead of
2852 // evaluating the same transcendental again. `-0.5 * magnSigma2` is a
2853 // scalar product folded before the elementwise multiply either way, so
2854 // scaling from the materialised factor gives the same values.
2855 thread_local Eigen::Array<double, Eigen::Dynamic, Eigen::Dynamic,
2856 Eigen::RowMajor>
2857 expdist;
2858 expdist = (-0.5 * dist.array()).exp();
2859 if (out_expdist != nullptr) *out_expdist = expdist;
2860 exp_factor = -0.5 * magnSigma2 * expdist;
2861
2862 for (Eigen::Index n = 0; n < dims.size(); ++n) {
2863 DK = (exp_factor * derivatives.D1[n].array()).matrix();
2864 if (compose_operators_ && usesGeodesicHeatKernel()) {
2865 DK += GeodesicHeat(geodesic_heat_kernel_)
2866 .covarianceBlock(x1, x2, dims(n) - 1, -1);
2867 }
2868 DKff.push_back(std::move(DK));
2869 }
2870}

◆ hasDistanceCache()

bool gpr::SexpatCF::hasDistanceCache ( ) const
inline

Definition at line 897 of file SexpatCF.h.

898 {
899 return dist_calculator_.hasCachedDistances();
900 }

◆ hasHierarchicalPrior()

bool gpr::SexpatCF::hasHierarchicalPrior ( ) const
inlinenodiscard

Definition at line 818 of file SexpatCF.h.

819 {
820 return use_hierarchical_prior_;
821 }

◆ hasPcLengthScalePrior()

bool gpr::SexpatCF::hasPcLengthScalePrior ( ) const
inlinenodiscardnoexcept

Definition at line 822 of file SexpatCF.h.

823 {
824 return use_pc_lengthscale_prior_;
825 }

◆ hessianPrecision()

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

Definition at line 89 of file SexpatCF.h.

90 {
91 return hessian_precision_;
92 }

◆ hierarchicalAnchored()

bool gpr::SexpatCF::hierarchicalAnchored ( Eigen::Index n) const
inlinenodiscardnoexcept

Definition at line 792 of file SexpatCF.h.

793 {
794 return n >= 0 &&
795 n < static_cast<Eigen::Index>(hierarchical_anchor_.size()) &&
796 hierarchical_anchor_[static_cast<std::size_t>(n)] != 0;
797 }

◆ hierarchicalPriorMu()

const Eigen::VectorXd & gpr::SexpatCF::hierarchicalPriorMu ( ) const
inlinenodiscardnoexcept

Definition at line 780 of file SexpatCF.h.

781 {
782 return hierarchical_mu_log_;
783 }

◆ hierarchicalPriorVariance()

double gpr::SexpatCF::hierarchicalPriorVariance ( Eigen::Index n) const
inlinenodiscardnoexcept

Variance of packed parameter ~n~ under the hierarchical prior.

Definition at line 799 of file SexpatCF.h.

801 {
802 if (n >= 0 && n < hierarchical_s2_log_per_.size() &&
803 hierarchical_s2_log_per_(n) > 0.0)
804 return hierarchical_s2_log_per_(n);
805 return hierarchical_s2_log_;
806 }

◆ lengthScalePriorWeights()

const Eigen::VectorXd & gpr::SexpatCF::lengthScalePriorWeights ( ) const
inlinenodiscardnoexcept

Definition at line 767 of file SexpatCF.h.

769 {
770 return length_prior_weight_;
771 }

◆ manifoldChart()

const std::shared_ptr< const geometry::InternalCoordinateChart > & gpr::SexpatCF::manifoldChart ( ) const
inlinenodiscardnoexcept

Definition at line 622 of file SexpatCF.h.

623 {
624 return manifold_chart_;
625 }

◆ manifoldDimensions()

Eigen::Index gpr::SexpatCF::manifoldDimensions ( ) const
inlinenodiscardnoexcept

Definition at line 626 of file SexpatCF.h.

627 {
628 return manifold_chart_ ? manifold_chart_->anchor().size() : 0;
629 }

◆ manifoldGeometryRowsEvaluatedForTesting()

std::size_t gpr::SexpatCF::manifoldGeometryRowsEvaluatedForTesting ( ) const
inlinenodiscardnoexcept

Definition at line 643 of file SexpatCF.h.

645 {
646 return manifold_geometry_rows_evaluated_for_testing_;
647 }

◆ manifoldJointEnergyGradientCovariance()

FieldMatrixd gpr::SexpatCF::manifoldJointEnergyGradientCovariance ( const Coord & positions) const
nodiscard

Definition at line 751 of file SexpatCF.cpp.

753{
754 if (!manifold_chart_ || chart_length_scale_.size() != 1) {
755 throw std::logic_error("Sexpat manifold covariance is not configured");
756 }
757 const Eigen::Index dimensions = manifold_chart_->anchor().size();
758 if (positions.cols() != dimensions) {
759 throw std::invalid_argument(
760 "Sexpat manifold covariance geometry dimension mismatch");
761 }
762 noteManifoldGeometryRows(positions.rows(), 0);
763 return Pullback(std::make_shared<ManifoldEnergyForceKernel>(
764 manifold_chart_, magnSigma2, chart_length_scale_(0, 0)))
765 .jointEnergyGradientCovariance(positions);
766}

◆ manifoldJointEnergyGradientCrossCovariance()

FieldMatrixd gpr::SexpatCF::manifoldJointEnergyGradientCrossCovariance ( const Coord & left_positions,
const Coord & right_positions ) const
nodiscard

Definition at line 768 of file SexpatCF.cpp.

770{
771 if (!manifold_chart_ || chart_length_scale_.size() != 1) {
772 throw std::logic_error("Sexpat manifold covariance is not configured");
773 }
774 const Eigen::Index dimensions = manifold_chart_->anchor().size();
775 if (left_positions.cols() != dimensions ||
776 right_positions.cols() != dimensions) {
777 throw std::invalid_argument(
778 "Sexpat manifold covariance geometry dimension mismatch");
779 }
780 noteManifoldGeometryRows(left_positions.rows(), right_positions.rows());
781 return Pullback(std::make_shared<ManifoldEnergyForceKernel>(
782 manifold_chart_, magnSigma2, chart_length_scale_(0, 0)))
783 .jointEnergyGradientCrossCovariance(left_positions, right_positions);
784}

◆ meanHessianVector()

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

Definition at line 609 of file SexpatCF.cpp.

614{
615 if (const auto kernel = assembledOperator())
616 return kernel->meanHessianVector(training, weights, position, direction,
617 action);
618 return Sexpat(*this).meanHessianVector(training, weights, position,
619 direction, action);
620}
friend class Sexpat
Definition SexpatCF.h:75

◆ predictMeanAlphaK()

void gpr::SexpatCF::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 )

Per-test-point predict mean (energy + gradient) via the Schmitz/Chmiela JPCL 2022 eq.6 alpha-K early contraction applied at the per-pair level.

For each test point m, accumulates into mu_E_out[m] and mu_G_out(m, beta) the SexpAt contribution to predict mean:

mu_E[m] += Sum_i alpha_E[i] * k(x_i, x_m)

  • Sum_i Sum_d alpha_G[i, d] * dk/dx_i^d mu_G[m, beta] += Sum_i alpha_E[i] * dk/dx_m^beta
    • Sum_i Sum_d alpha_G[i, d] * d^2k/(dx_i^d dx_m^beta)

Cost: O(num_train * n_pairs) per test point instead of the O(num_train * num_test * D^2) of the legacy per-(d1, d2) loop.

alpha_G_flat layout matches the existing accumulator's weights vector: alpha_G_flat[d * num_train + i] is the gradient alpha for training point i, atomic-coord dim d (1-based d, i.e. uDdim[k] for k in 0..D-1; entries at d=0 are alpha_E and live separately in alpha_E).

Outputs are ACCUMULATED in place (callers zero them first). RowMajor mu_G_out keeps the layout consistent with image1.G in calculatePotential.

Math notes:

  • Per pair p in a pairtype, the per-pair gradient du_p/dx_alpha is nonzero on only 6 atomic-coord slots (3 per atom in the pair; 3 for moving-frozen pairs).
  • The D12 fold collapses to a per-pair scalar c_i_p = Sum over 6 x-slots of alpha_G[i, d] * du_p/dx_i^d, verified rank-1 per pair by python/tests/test_sympy_alpha_k_d12.py.
  • Convention: dist returned by dist_at_cached_sq is 2 * Sum_p (1/l_p^2) * (u_p_i - v_p_m)^2; k = magn * exp(-0.5 * dist).

Definition at line 2872 of file SexpatCF.cpp.

2880{
2881 Sexpat(*this).predictMeanAlphaK(x_train, x_test, alpha_E, alpha_G_flat,
2882 mu_E_out, mu_G_out);
2883}

◆ predictMeanAlphaKPrepared()

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

Definition at line 2894 of file SexpatCF.cpp.

2900{
2901 Sexpat(*this).predictMeanAlphaKPrepared(prepared, x_test, mu_E_out,
2902 mu_G_out);
2903}

◆ prepareAlphaK()

bool gpr::SexpatCF::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

Definition at line 2885 of file SexpatCF.cpp.

2889{
2890 return Sexpat(*this).prepareAlphaK(x_train, alpha_E, alpha_G_flat,
2891 prepared);
2892}

◆ priorState()

PriorState gpr::SexpatCF::priorState ( ) const
inlinenodiscard

Definition at line 842 of file SexpatCF.h.

843 {
844 return {prior_parameters_gaussian, prior_parameters_sqrtt,
845 prior_parameters_lognormal, use_lognormal_magn_prior_,
846 use_hierarchical_prior_, length_prior_weight_,
847 hierarchical_mu_log_, hierarchical_s2_log_,
848 hierarchical_s2_log_per_, hierarchical_anchor_,
849 use_pc_lengthscale_prior_, pc_lambda_};
850 }

◆ rescaleGeodesicHeatCovariance()

void gpr::SexpatCF::rescaleGeodesicHeatCovariance ( double factor)

Convert the additive component to a different output variance unit.

Definition at line 710 of file SexpatCF.cpp.

711{
712 if (!std::isfinite(factor) || !(factor > 0.0))
713 throw std::invalid_argument(
714 "geodesic covariance scale must be finite and positive");
715 if (!geodesic_heat_kernel_ || factor == 1.0) return;
716 geodesic_heat_kernel_ =
717 std::make_shared<const GeodesicHeatEnergyForceKernel>(
718 geodesic_heat_kernel_->withCovarianceWeight(
719 factor * geodesic_heat_kernel_->covarianceWeight()));
721}

◆ resetManifoldGeometryRowsEvaluatedForTesting()

void gpr::SexpatCF::resetManifoldGeometryRowsEvaluatedForTesting ( ) const
inlinenoexcept

Definition at line 634 of file SexpatCF.h.

635 {
636 manifold_geometry_rows_evaluated_for_testing_ = 0;
637 }

◆ restorePriorState()

void gpr::SexpatCF::restorePriorState ( PriorState state)
inline

Definition at line 851 of file SexpatCF.h.

852 {
853 prior_parameters_gaussian.setParameters(state.gaussian);
854 prior_parameters_sqrtt.setParameters(state.sqrtt);
855 prior_parameters_lognormal.setParameters(state.lognormal);
856 use_lognormal_magn_prior_ = state.use_lognormal_magn;
857 use_hierarchical_prior_ = state.use_hierarchical;
858 length_prior_weight_ = std::move(state.length_prior_weight);
859 hierarchical_mu_log_ = std::move(state.hierarchical_mu_log);
860 hierarchical_s2_log_ = state.hierarchical_s2_log;
861 hierarchical_s2_log_per_ = std::move(state.hierarchical_s2_log_per);
862 hierarchical_anchor_ = std::move(state.hierarchical_anchor);
863 use_pc_lengthscale_prior_ = state.use_pc_lengthscale;
864 pc_lambda_ = std::move(state.pc_lambda);
865 }

◆ setConfInfo()

void gpr::SexpatCF::setConfInfo ( const AtomsConfiguration & value)
inline

Definition at line 38 of file SexpatCF.inl.

39{
41 conf_info = value;
42}

◆ setFarFieldRadius()

void gpr::SexpatCF::setFarFieldRadius ( double radius)
inline

Frozen atoms at or beyond radius use the dipole tensor. Zero keeps the exact inverse-distance pairs.

Definition at line 32 of file SexpatCF.inl.

33{
34 dist_calculator_.setFarFieldRadius(radius);
35 far_field_radius_ = dist_calculator_.farFieldRadius();
36}

◆ setGeodesicHeatKernel()

void gpr::SexpatCF::setGeodesicHeatKernel ( std::shared_ptr< const GeodesicHeatEnergyForceKernel > kernel)

Attach an immutable heat component with its own reference and metric.

Definition at line 519 of file SexpatCF.cpp.

521{
522 if (kernel && kernel->dimensions() != 3 * conf_info.atoms_mov.type.size())
523 throw std::invalid_argument(
524 "geodesic heat component has incompatible Cartesian dimensions");
525 if (kernel && kernel->covarianceWeight() == 0.0) kernel.reset();
526 geodesic_heat_kernel_ = std::move(kernel);
528}

◆ setGeodesicHeatReferencePath()

void gpr::SexpatCF::setGeodesicHeatReferencePath ( const Coord & reference_path,
double covariance_weight )

Attach a geodesic heat summand to the selected pair or chart base. A zero covariance weight disables it.

Definition at line 530 of file SexpatCF.cpp.

532{
533 if (covariance_weight == 0.0) {
535 return;
536 }
537 setGeodesicHeatKernel(std::make_shared<const GeodesicHeatEnergyForceKernel>(
538 reference_path, conf_info, lengthScale, covariance_weight));
539}
void setGeodesicHeatKernel(std::shared_ptr< const GeodesicHeatEnergyForceKernel > kernel)
Attach an immutable heat component with its own reference and metric.
Definition SexpatCF.cpp:519

◆ setHessianPrecision()

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

Definition at line 85 of file SexpatCF.h.

86 {
87 hessian_precision_ = precision;
88 }

◆ setHierarchicalAnchorMask()

void gpr::SexpatCF::setHierarchicalAnchorMask ( std::vector< char > mask)
inline

Length scales (index into the length-scale block) the population prior anchors: under the classic joint energy/force prior of the gprd profiles these take the per-type log-Gaussian in place of the classic term; the others keep the classic term.

Definition at line 788 of file SexpatCF.h.

789 {
790 hierarchical_anchor_ = std::move(mask);
791 }

◆ setHierarchicalPrior() [1/2]

void gpr::SexpatCF::setHierarchicalPrior ( const Eigen::VectorXd & mu_log,
double s2_log )
inline

Definition at line 129 of file SexpatCF.inl.

131{
132 hierarchical_mu_log_ = mu_log;
133 hierarchical_s2_log_ = s2_log;
134 hierarchical_s2_log_per_.resize(0);
135 use_hierarchical_prior_ = (mu_log.size() > 0 && s2_log > 0.0);
136}

◆ setHierarchicalPrior() [2/2]

void gpr::SexpatCF::setHierarchicalPrior ( const Eigen::VectorXd & mu_log,
double s2_log,
const Eigen::VectorXd & s2_log_per )
inline

The same prior with a variance per packed parameter (the shared ~s2_log~ where an entry is not positive): the population prior of a pair type sets its own width.

Definition at line 138 of file SexpatCF.inl.

141{
142 setHierarchicalPrior(mu_log, s2_log);
143 hierarchical_s2_log_per_ =
144 s2_log_per.size() == mu_log.size() ? s2_log_per : Eigen::VectorXd();
145 // A prior with no shared width still applies to the parameters that
146 // carry their own.
147 use_hierarchical_prior_ =
148 mu_log.size() > 0 &&
149 (s2_log > 0.0 || (hierarchical_s2_log_per_.array() > 0.0).any());
150}
void setHierarchicalPrior(const Eigen::VectorXd &mu_log, double s2_log)
Definition SexpatCF.inl:129

◆ setLengthScale()

void gpr::SexpatCF::setLengthScale ( double value)
inline

Definition at line 24 of file SexpatCF.inl.

25{
26 auto& lengths = getLengthScaleRef();
27 if (lengths.size() == 0) lengths.resize(1, 1);
28 lengths.setConstant(value);
30}

◆ setLengthScalePriorWeights()

void gpr::SexpatCF::setLengthScalePriorWeights ( const Eigen::VectorXd & weights)
inline

Enable a hierarchical-Bayes Gaussian prior on the log-space kernel parameters: ~log(theta_i) ~ N(mu_log, s2_log * I)~ where ~mu_log~ is the packed log-parameter target (~[log(magnSigma2), log(lengthScale[0]), ..., log(lengthScale[K-1])]~, same layout as ~combineParameters()~) and ~s2_log~ is the shared variance. When enabled, ~calculateLogPrior~ / ~calculateLogPriorGradient~ use this hierarchical density instead of the global-GP zero-prior branch. The density operates in log-space directly, so no linear-to-log Jacobian terms are added (the SCG optimiser already runs on the packed log-parameters returned by ~combineParameters~).

Per-image GP fits use ~mu_log = theta_global~ from the session GP's MAP and a shared ~s2_log = tau^2~ regulariser that pulls per-image ~theta_i~ back toward the global MAP when the per-image data set is small. Per-length-scale weights of the prior terms; empty restores one prior per length scale.

Definition at line 763 of file SexpatCF.h.

764 {
765 length_prior_weight_ = weights;
766 }

◆ setMagnSigma2()

void gpr::SexpatCF::setMagnSigma2 ( double value)
inline

Definition at line 19 of file SexpatCF.inl.

20{
21 magnSigma2 = value;
22}

◆ setManifoldChart()

void gpr::SexpatCF::setManifoldChart ( std::shared_ptr< const geometry::InternalCoordinateChart > chart,
double length_scale )

Attach a chart so assembly can wrap this primitive as Pullback(SE, chart). Sexpat itself stays the inverse-distance kernel.

Definition at line 495 of file SexpatCF.cpp.

498{
499 if (!chart || !chart->valid()) {
500 throw std::invalid_argument(
501 "Sexpat manifold dispatch requires a valid tangent chart");
502 }
503 if (!(length_scale > 0.0) || !std::isfinite(length_scale)) {
504 throw std::invalid_argument(
505 "Sexpat manifold length scale must be positive and finite");
506 }
507 manifold_chart_ = std::move(chart);
508 chart_length_scale_.resize(1, 1);
509 chart_length_scale_(0, 0) = length_scale;
511}

◆ setModelProfile()

void gpr::SexpatCF::setModelProfile ( GPModelProfile profile)
inline

Definition at line 118 of file SexpatCF.inl.

119{
120 model_profile_ = profile;
124 // Chart and heat components have independent configuration; choosing
125 // a hyperparameter prior preserves the assembled covariance.
126 }
127}
void clearHierarchicalPrior()
Definition SexpatCF.inl:152
void clearPcLengthScalePrior()
Definition SexpatCF.inl:167

◆ setParameters()

void gpr::SexpatCF::setParameters ( const Eigen::VectorXd & w)
inline

Set parameters of this covariance function using the provided vector.

Parameters
wVector of combined parameters from covariance functions and likelyhood

Definition at line 44 of file SexpatCF.inl.

45{
46 auto& lengths = getLengthScaleRef();
47 magnSigma2 = numerics::exp(w(0));
48 for (Eigen::Index n = 0; n < lengths.size(); ++n)
49 *(lengths.data() + n) = numerics::exp(w(n + 1));
51}

◆ setPcLengthScalePrior()

void gpr::SexpatCF::setPcLengthScalePrior ( const Eigen::VectorXd & lambda)
inline

Penalized-Complexity length-scale prior for the global GP. lambda is the per-pairtype PC rate (lambda_k = -rho0_k * ln(alpha)); element k applies to lengthScale[k]. magnSigma2 is left unpenalised.

Definition at line 161 of file SexpatCF.inl.

162{
163 pc_lambda_ = lambda;
164 use_pc_lengthscale_prior_ = (lambda.size() > 0);
165}

◆ setPriorParametersGaussian()

void gpr::SexpatCF::setPriorParametersGaussian ( const PriorBase & prior)
inline

Definition at line 78 of file SexpatCF.inl.

79{
80 prior_parameters_gaussian.setParameters(prior);
81}

◆ setPriorParametersLogNormal()

void gpr::SexpatCF::setPriorParametersLogNormal ( const PriorBase & prior)
inline

Parameters of the optional log-normal prior on magnSigma2. Inactive until setUseLogNormalMagnPrior(true).

Definition at line 88 of file SexpatCF.inl.

89{
90 prior_parameters_lognormal.setParameters(prior);
91}

◆ setPriorParametersSqrtt()

void gpr::SexpatCF::setPriorParametersSqrtt ( const PriorBase & prior)
inline

Definition at line 83 of file SexpatCF.inl.

84{
85 prior_parameters_sqrtt.setParameters(prior);
86}

◆ setUseLogNormalMagnPrior()

void gpr::SexpatCF::setUseLogNormalMagnPrior ( bool enabled)
inlinenoexcept

Opt-in log-normal prior on the positive signal variance magnSigma2. Off (the default) keeps the half-Student-t magnitude prior on classic profiles and the half-Cauchy magnitude prior in the MAP objective.

Definition at line 108 of file SexpatCF.inl.

109{
110 use_lognormal_magn_prior_ = enabled;
111}

◆ setUseLongDoubleHessian()

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

Definition at line 93 of file SexpatCF.h.

94 {
95 hessian_precision_ =
96 enabled ? HessianPrecision::LongDouble : HessianPrecision::Double;
97 }

◆ trainingGradientAlphaK()

void gpr::SexpatCF::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 )

Accumulate joint energy/force quadratic derivatives. Distributed execution is collective; local calls do not enter MPI. The optional count reports the unique training pairs evaluated by this rank.

Definition at line 2905 of file SexpatCF.cpp.

2910{
2911 Sexpat(*this).trainingGradientAlphaK(x_train, alpha_E, alpha_G_flat,
2912 quad_out, distributed,
2913 local_pair_count, process_group);
2914}

◆ useLogNormalMagnPrior()

bool gpr::SexpatCF::useLogNormalMagnPrior ( ) const
inlinenodiscardnoexcept

Definition at line 113 of file SexpatCF.inl.

114{
115 return use_lognormal_magn_prior_;
116}

◆ useLongDoubleHessian()

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

Definition at line 98 of file SexpatCF.h.

99 {
100 return hessian_precision_ == HessianPrecision::LongDouble;
101 }

◆ usesGeodesicHeatKernel()

bool gpr::SexpatCF::usesGeodesicHeatKernel ( ) const
inlinenodiscardnoexcept

Definition at line 664 of file SexpatCF.h.

665 {
666 return static_cast<bool>(geodesic_heat_kernel_);
667 }

◆ usesManifoldChart()

bool gpr::SexpatCF::usesManifoldChart ( ) const
inlinenodiscardnoexcept

Definition at line 616 of file SexpatCF.h.

617 {
618 return static_cast<bool>(manifold_chart_);
619 }

◆ Sexpat

friend class Sexpat
friend

Definition at line 75 of file SexpatCF.h.


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