Loading...
Searching...
No Matches
gpr Namespace Reference

Gaussian-process regression, kernels, priors, and the searches that run on the surrogate. More...

Namespaces

namespace  abi
namespace  bo
namespace  capi
namespace  cli
namespace  coord
namespace  derivatives
namespace  extended
namespace  field
namespace  geometry
namespace  htst
namespace  io
namespace  irc
 Intrinsic reaction coordinate drivers in mass-weighted coordinates.
namespace  itergp
namespace  kokkos_environment
namespace  laplace
namespace  linalg
 Dense and structured linear algebra behind the GP: Cholesky and eigen solvers, linear operators, backend selection.
namespace  memory
namespace  neb
 The nudged elastic band: path, GP-NEB driver, configuration and result, acquisition, IDPP start.
namespace  numerics
namespace  optim
namespace  optim_abi
namespace  pairlocal
namespace  policy
namespace  posterior
namespace  potentials
 Analytical test potentials and potentials built from a fitted GP.
namespace  priors
 Prior distributions and prior-mean functions for the GP.
namespace  quantum
 Models for quantum-path (instanton) searches: arc and tail actions, amplitude continuation.
namespace  readcon_abi
namespace  readcon_db_abi
namespace  rgmin_abi
namespace  rgpot_abi
namespace  runtime
namespace  sfc
namespace  ski
namespace  startup
namespace  track
namespace  uasaddle
namespace  vecchia

Classes

struct  AdamOptimizationSettings
 ADAM-specific settings (learning rate, decay, momentum, AMSGrad). More...
class  AdditivePairKernel
class  ARDGridSearch
 Grid search over ARD lengthscales + noise. More...
struct  ARDSearchResult
 Result of ARD grid search. More...
struct  AtomicEnvironments
class  AtomicInducingPosterior
struct  AtomsConfiguration
 Stores configurations of all atoms in the system. More...
struct  AtomsPositionAndType
 Structure of atoms positions and types. More...
class  BayesianModelAveraging
 Bayesian model averaging over hyperparameter grid. More...
struct  BMAPrediction
 Prediction result from Bayesian model averaging. More...
struct  BorderedNoiseReport
struct  BorderedVarianceInterval
struct  CanonicalDimerDefaultOptions
struct  CeresOptimizationSettings
 Ceres-specific settings (currently only the common fields). More...
class  ConditionalKernelProjection
class  ConditionalPosterior
class  ConditionedKernel
class  ConstantCF
 Constant covariance function. More...
class  ConstrainedChartCovariance
struct  CutoffPairFeature
struct  Derivatives
 Structure of directional derivatives. More...
struct  DeviceResidency
struct  EnergyAndGradient
 Structure of energy and gradient stored in Eigen-compatible form. More...
struct  EnergySurfaceOutputInfo
 A structure with information used to write the energy surface to a file. More...
struct  FactoredTrainingGeometry
class  FactorizedLikelihood
class  FeatomicEnvironmentDescriptor
class  GaussianProcessRegression
class  GeodesicCovarianceEvidence
class  GeodesicHeat
class  GeodesicHeatEnergyForceKernel
struct  GPRSetup
 Structure of GPR properties. More...
struct  Indices2D
 Structure of pair of indices. More...
struct  INLAPrediction
struct  InputParameters
 Structure of the input parameters. All input parameters are pairs of string names and values. More...
class  InverseDistanceDescriptor
 Inverse distance descriptor for molecular configurations. More...
struct  IterationsLimits
 Structure of limits for iterational loops. More...
struct  JointObservationVarianceReduction
class  KernelOperator
struct  KeyValuePair
 Structure of a string key and template value. More...
class  Kronecker
class  LaplaceINLA
 Laplace / INLA uncertainty quantifier over GP/TP hyperparameters. More...
struct  LazyFactoredTrainingGeometry
struct  LBFGSInfo
 Structure with information for the LBFGS method. More...
class  LikGaussian
 Gaussian noise with variance. More...
class  LowRankCholesky
class  ManifoldEnergyForceKernel
class  Matern52
class  ModeRefitPolicy
class  MpiLifetime
 A native entry point finalizes only the MPI world it initializes. More...
class  NoiseGridSearch
 Exponential grid search over noise hyperparameter. More...
struct  NoiseSearchResult
 Result of a noise grid search. More...
struct  Observation
 Observation data: energy, gradient and positions. More...
class  ObservationLikelihood
 Contract for non-Gaussian observation models used by the INLA inner Laplace step (Rasmussen-Williams Algorithm 3.1). More...
struct  OptimizerCommonSettings
 Settings shared by every hyperparameter optimizer. More...
struct  Pair
 A simple pair with identical datatypes. More...
class  PairCutoff
struct  PhaseTimers
struct  PhaseTotals
class  PriorBase
 Class of prior parameters. More...
class  PriorGaussian
 Gaussian prior. More...
class  PriorLogNormal
 Log-normal prior. More...
class  PriorLogUnif
 Uniform prior for the logarithm of the parameter. More...
class  PriorSqrtt
 Student-t prior for the square root of the parameter. More...
class  PriorT
 Student-t prior. More...
class  PriorUnif
 Uniform prior. More...
class  Project
struct  PublicLayoutBytes
class  Pullback
struct  RadialPairFeature
class  RandomFourierFeatures
 Random Fourier Features for SE kernel approximation. More...
struct  RFFFeatureSelection
 Measured result of one automatic selection. Unmeasured errors stay NaN. More...
class  RFFFeatureSelectionError
class  RFFModel
 Random Fourier Features (RFF) approximation to the SE kernel. More...
struct  RFFValidationPlan
struct  RigidDeflationDiagnostic
struct  SaddleCertificate
 Final-saddle certificate, split from the exploration radius. More...
struct  ScaleFreeTrustConfig
 Dimensionless knobs. All O(1) and metric-independent by construction. More...
class  ScaleFreeTrustRegion
 Self-tuning scale-free trust region (state = the current radius). More...
struct  ScgOptimizationSettings
 SCG-specific settings (trust-region scale, log-magnSigma2 barriers, curvature mode). More...
class  ScopedPhaseTimer
class  ScopedPredictTimer
class  ScopedVarianceTimer
class  Sexpat
class  SexpatCF
 Pair-type inverse-distance squared-exponential primitive. More...
struct  SexpatLocalOracleScope
class  SpeciesEnvironmentKernel
class  StableBasis1D
class  StableBasisND
struct  StableBasisPosteriorWeights
class  StationaryChartKernel
struct  StopCriteriaForDimer
 Stores stop criteria for dimer method (e.g. LBFGS). More...
struct  StructuredPermutation
class  StudentTProcessRegression
class  Sum
struct  SupportedAtomicEnvironments
struct  TrainingKernelGeometry
struct  TrainingKernelGeometryBlock
struct  TrainingKernelGeometrySubset
struct  TransitionParameters
 Structure of translation parameters. More...
struct  Triplet
 A simple triplet with identical datatypes. More...
class  TrustRadius
 Trust radius enforcement for GP surrogate models. More...
class  WallClockLimit
class  WallClockLimitReached

Concepts

concept  DifferentiableRadial
 Value and both derivatives with respect to one squared distance.

Typedefs

using Index_t = uint32_t
using EigenMatrix
using FieldMatrixd
using FieldMatrixi
using FieldMatrixIdx
using FieldMatrixU8
using Coord = FieldMatrixd
using vector3_reg = Eigen::Vector3d
using CutoffPairFeatures = std::vector<CutoffPairFeature>
using RefusalAwareHessianAction
 Hessian action that reports whether an exact child refused.
using RefusalAwareHessianPreparation
 Query preparation that reports whether an exact child refused.
using KernelMatrixBuilder
 Kernel matrix builder: given lengthscales and noise, return K_XX.

Enumerations

enum class  ChartScalarKernel { SquaredExponential , Matern52 }
enum class  HyperparameterOptimizationMode {
  SCG , INLA , MAP_LBFGS , RGMIN_SCG ,
  RGMIN_OPT
}
enum class  HyperparameterObjectiveMode { NLML , LOO , LOCAL_LOO }
enum class  PriorMeanStatistic { Mean , Maximum }
 Gaussian Process Regression algorithm. More...
enum class  BorderedSchurSign { ClampNegative , PreserveSigned }
enum class  MapPriorWeightMode : uint8_t { Annealed = 0 , Full = 1 }
enum class  ScgCurvatureMode { EXACT = 0 , FINITE_DIFFERENCE = 1 , NLML_HESSIAN_VECTOR = 2 }
 Selects how SCG computes the directional curvature term. More...
enum class  UncertaintyMode {
  MAP = 0 , BMA = 1 , LAPLACE = 2 , EB = 3 ,
  SVGD = 4 , LAPLACE_SLICE = 5
}
enum class  GPModelProfile : uint8_t { CHEMGP = 0 , GPRD_ZBL = 1 , EXTENDED = 2 }

Functions

std::optional< ConvergenceNormType > parseForceNorm (std::string_view name)
std::string_view forceNormName (std::optional< ConvergenceNormType > norm)
template<class Derived>
double forceNorm (const Eigen::MatrixBase< Derived > &force, ConvergenceNormType norm)
template<class Derived>
double forceDualNorm (const Eigen::MatrixBase< Derived > &direction, ConvergenceNormType norm)
std::vector< CutoffPairFeatures > cutoffPairFeatures (const Coord &positions, const AtomsConfiguration &configuration)
 Sorted pair features for each configuration; absent pairs are exact zeros.
std::vector< CutoffPairFeatures > radialPairFeatures (const Coord &positions, const AtomsConfiguration &configuration)
std::vector< CutoffPairFeatures > radialPairFeatures (const Coord &positions, const AtomsConfiguration &configuration, double far_radius)
std::vector< FieldMatrixd > cutoffPairSquaredDistances (const Coord &left, const Coord &right, const AtomsConfiguration &configuration, const FieldMatrixd &lengths)
std::vector< FieldMatrixd > radialPairSquaredDistances (const Coord &left, const Coord &right, const AtomsConfiguration &configuration, const FieldMatrixd &lengths, double far_radius)
template<typename Function>
void forEachCutoffPair (const CutoffPairFeatures &left, const CutoffPairFeatures &right, Function &&function)
 Visit the union of two sparse feature rows in their common pair vocabulary.
std::string sha256Hex (const void *data, std::size_t size)
 Lowercase hexadecimal SHA-256 digest of a byte range (FIPS 180-4).
std::string sha256File (const std::string &path)
 Digest of a file's contents; empty when the file cannot be read.
bool conditionKernelMatrix (const Eigen::MatrixXd &joint, const std::vector< Eigen::MatrixXd > &derivatives, Eigen::Index anchor_rows, Eigen::Index query_rows, Eigen::Index dimensions, const Eigen::VectorXd &anchor_noise, Eigen::MatrixXd &covariance, std::vector< Eigen::MatrixXd > &conditional_derivatives)
bool conditionKernelMatrix (const Eigen::MatrixXd &joint, const std::vector< Eigen::MatrixXd > &derivatives, Eigen::Index anchor_rows, Eigen::Index query_rows, Eigen::Index dimensions, const Eigen::VectorXd &anchor_noise, Eigen::MatrixXd &covariance, std::vector< Eigen::MatrixXd > &conditional_derivatives, const linalg::LocalExecutor &execution)
KernelOperator::CrossCovarianceFunction makeKernelCrossCovariance (std::shared_ptr< const KernelOperator > kernel, const Eigen::MatrixXd &training)
KernelOperator::MeanFunction makeKernelMean (std::shared_ptr< const KernelOperator > kernel, const Eigen::MatrixXd &training, const Eigen::VectorXd &weights)
 Owning fitted mean, using the kernel's representation or its exact product.
KernelOperator::MeanHessianFunction makeAnalyticKernelMeanHessianVector (const std::shared_ptr< const KernelOperator > &kernel, const Eigen::MatrixXd &training, const Eigen::VectorXd &weights)
KernelOperator::MeanHessianPreparation makeAnalyticKernelMeanHessian (const std::shared_ptr< const KernelOperator > &kernel, const Eigen::MatrixXd &training, const Eigen::VectorXd &weights)
KernelOperator::MeanHessianFunction makeKernelMeanHessianVector (std::shared_ptr< const KernelOperator > kernel, const Eigen::MatrixXd &training, const Eigen::VectorXd &weights)
RefusalAwareHessianPreparation makeRefusalAwareKernelMeanHessian (std::shared_ptr< const KernelOperator > kernel, const Eigen::MatrixXd &training, const Eigen::VectorXd &weights, bool *all_exact=nullptr, bool *has_exact_or_refusal=nullptr)
 Prepare a fitted kernel Hessian action that propagates exact-child refusals through composite operators.
KernelOperator::MeanHessianPreparation makeKernelMeanHessian (std::shared_ptr< const KernelOperator > kernel, const Eigen::MatrixXd &training, const Eigen::VectorXd &weights)
KernelOperator::MeanHessianMatrixFunction makeKernelMeanHessianMatrix (std::shared_ptr< const KernelOperator > kernel, const Eigen::MatrixXd &training, const Eigen::VectorXd &weights)
 Dense mean Hessian of a kernel from the columns of its refusal-aware action. A failed column is Refused when an exact child refused it and Unavailable when only a generic child missed; the matrix is left empty in both cases.
std::shared_ptr< const KernelOperator > makeChartScalarKernel (std::shared_ptr< const geometry::CoordinateChart > chart, double magnitude_variance, double length_scale, ChartScalarKernel kernel=kDefaultChartScalarKernel)
 Squared-exponential Pullback unless kernel is Matern52.
bool ownsBlock (long block_idx, int rank, int nprocs, bool serial_per_rank)
bool ownsBlockIfReduce (long block_idx, int rank, int nprocs, bool do_reduce)
bool buildFactoredTrainingGeometry (const AtomsConfiguration &conf_info, const FieldMatrixd &x_loc, FactoredTrainingGeometry &out, double far_field_radius=0.0)
bool buildCrossBlockDerivativesFactored (const FactoredTrainingGeometry &factors, Index_t block_n, Index_t block_m, uint8_t derivative_options, SexpatCF::CrossBlockGeometry &out)
const SexpatCF::CrossBlockGeometry * resolveTrainingBlockGeometry (const SexpatCF &covariance, const TrainingKernelGeometry &geom, const TrainingKernelGeometryBlock &block, SexpatCF::CrossBlockGeometry &scratch)
double lengthscaleProjectionFloor (double max_pair_distance, double absolute_floor)
Eigen::MatrixXd hssvdHermiteCartesianAction (const Eigen::MatrixXd &jacobian, const Eigen::MatrixXd &residuals, const Eigen::MatrixXd &force_weights, const Eigen::VectorXd &energy_kernel_weights, const Eigen::VectorXd &force_kernel_weights, const Eigen::VectorXd &force_residual_dots, double energy_kernel_weight_sum, double force_kernel_residual_dot_sum, const Eigen::MatrixXd &directions)
bool arrowheadEigenpairs (const Eigen::Ref< const Eigen::VectorXd > &diagonal, const Eigen::Ref< const Eigen::VectorXd > &spike, double corner, Eigen::VectorXd &evals, Eigen::MatrixXd &evecs)
bool extendSymmetricSpectrum (const Eigen::Ref< const Eigen::MatrixXd > &grown, const Eigen::Ref< const Eigen::VectorXd > &diagonal, const Eigen::Ref< const Eigen::MatrixXd > &basis, Eigen::VectorXd &evals, Eigen::MatrixXd &evecs)
bool priorFreeReplicatedInverse (bool cholmod, bool scalapack, bool slate, bool unregularized, bool use_hssvd_gradient)
bool useDenseFactorForTrace (bool prior_free_inverse, bool use_hssvd_gradient, bool distributed_factor, long long factor_rows, long long factor_cols, long long target_size)
RFFValidationPlan planRFFFeatureValidation (int n_geometries, int cartesian_dimension, std::uint64_t memory_cap_bytes)
std::vector< int > rffFarthestPointOrder (const Eigen::MatrixXd &positions)
std::string formatRFFFeatureSelection (const RFFFeatureSelection &report)
bool looCalibrationIsUnityFromCholeskyDiagonal (const Eigen::VectorXd &alpha, const Eigen::VectorXd &diagonal)
double looVarianceCalibrationFactor (const Eigen::VectorXd &alpha, const Eigen::VectorXd &inv_diag)
bool stabilizePosteriorCovariance (Eigen::MatrixXd &covariance)
 Project a rounded covariance onto the positive-semidefinite cone while preserving its nonnegative diagonal exactly.
bool subtractStableBasisProjectedCrossCovariance (const StableBasisND &basis, const Eigen::MatrixXd &Kstar, const Eigen::MatrixXd &Kright, const Eigen::MatrixXd &prior, double total_sigma2, Eigen::MatrixXd &K_post, bool contracted_mean=false, Eigen::Index left_queries=1, Eigen::Index right_queries=1)
Eigen::VectorXd applyStableBasisStatisticalInverse (const StableBasisND &basis, const Eigen::VectorXd &rhs, double noise)
bool subtractStableBasisProjectedCrossCovariance (const StableBasisND &basis, const EigenMatrix &Kstar, const EigenMatrix &Kright, const EigenMatrix &prior, const double total_sigma2, EigenMatrix &K_post, bool contracted_mean, Eigen::Index left_queries, Eigen::Index right_queries)
std::optional< JointObservationVarianceReduction > jointObservationVarianceReduction (Eigen::MatrixXd candidate_covariance, const Eigen::MatrixXd &target_candidate_covariance, const double target_variance, const double noise_variance)
std::optional< JointObservationVarianceReduction > jointObservationVarianceReduction (const Eigen::MatrixXd &posterior_covariance, Eigen::Index query_count, Eigen::Index dimensions, Eigen::Index candidate_query, const std::vector< Eigen::Index > &target_queries, double noise_variance)
 Integrated variance reduction from one joint energy-force query.
std::optional< JointObservationVarianceReduction > jointObservationForceVarianceReduction (const Eigen::MatrixXd &posterior_covariance, Eigen::Index query_count, Eigen::Index dimensions, Eigen::Index candidate_query, const std::vector< Eigen::Index > &target_queries, double noise_variance)
 Integrated force-variance reduction from one joint energy-force query.
Eigen::VectorXd findFMode (const EigenMatrix &K, const Eigen::VectorXd &y, const ObservationLikelihood &ol, int max_iter=30, double tol=1e-8)
 Posterior mode f_mode = argmax_f [log p(y|f) + log N(f | 0, K)] via the Rasmussen-Williams safe Newton recursion (Algo 3.1).
double laplaceMarginalLogLik (const EigenMatrix &K, const Eigen::VectorXd &y, const Eigen::VectorXd &f_mode, const ObservationLikelihood &ol)
 Laplace approximation to log p(y | theta) given prior K and the converged posterior mode f_mode (R&W eq. 3.32):
StructuredPermutation buildStructuredPermutation (const Eigen::VectorXd &ind_Ddim)
StructuredPermutation buildObservationTiledPermutation (const Eigen::VectorXd &ind_Ddim)
Eigen::VectorXd permuteVector (const Eigen::VectorXd &input, const StructuredPermutation &p)
Eigen::VectorXd unpermuteVector (const Eigen::VectorXd &input, const StructuredPermutation &p)
EigenMatrix permuteMatrixRows (const EigenMatrix &input, const StructuredPermutation &p)
EigenMatrix unpermuteMatrixRows (const EigenMatrix &input, const StructuredPermutation &p)
EigenMatrix permuteSymmetricMatrix (const EigenMatrix &input, const StructuredPermutation &p)
EigenMatrix unpermuteSymmetricMatrix (const EigenMatrix &input, const StructuredPermutation &p)
void requireWallClock (const std::shared_ptr< const WallClockLimit > &limit)
bool collectiveWallClockLimitReached (const std::shared_ptr< const WallClockLimit > &limit, const linalg::MpiContext &context)
bool collectiveWallClockLimitReached (const std::shared_ptr< const WallClockLimit > &limit)
 The oracle/search process group, with a local fallback outside MPI.
double medianPairwiseDistance (const EigenMatrix &R_train)
 Median of the strict-upper-triangle pairwise Euclidean row distances over a training set. Degree-1 homogeneous: median(s*X) = s*median(X).
SaddleCertificate certifyFinalSaddle (double true_pes_saddle_force, double conv_tol, const std::vector< double > &per_image_variance, double variance_envelope)
 Combined force and variance criterion for callers that request it. The variance envelope is an optional exploration condition. A physical saddle additionally requires an independent assessment of its Hessian index; neither this helper nor a trust radius establishes that index.
void applyCanonicalReadconDimerDefaults (InputParameters &parameters, const CanonicalDimerDefaultOptions &options={})
 Apply the canonical readcon dimer defaults to parameters.
CanonicalDimerDefaultOptions gprdUnflaggedDimerOptions ()
void applyGprdDimerDefaults (InputParameters &parameters, const CanonicalDimerDefaultOptions &options)
bool defaultDimerImage1EachPhase (const bool use_hssvd, const bool) noexcept
void requirePositiveFinitePriorParameter (const char *density, const char *name, double value)
void requireFinitePriorParameter (const char *density, const char *name, double value)
PublicLayoutBytes libraryPublicLayout ()
PublicLayoutBytes consumerPublicLayout ()
constexpr bool iterationAllowedByLimit (Index_t iteration, Index_t configured_limit) noexcept
bool usesClassicJointEnergyForcePrior (GPModelProfile profile) noexcept
bool launchedOnOneNode () noexcept
void excludeLibfabricBtlOnOneNode () noexcept
int reportFatal (const char *program, const char *what) noexcept
template<class Matrices, class Body>
void assembleCollectively (const MpiContext &context, Matrices &result, const Body &body)
void writeBMAOutput (const Eigen::VectorXd &flat, Index_t N_im, Index_t D, Observation &image1)
void addConstantCovarianceBlock (ConstantCF *const_cov_fun, const Eigen::VectorXd &row_indices, const Eigen::VectorXd &col_indices, EigenMatrix &matrix)
void addConstantCovarianceBlock (ConstantCF *const_cov_fun, const Eigen::VectorXd &row_indices, const Eigen::VectorXd &col_indices, EigenMatrix &matrix)
double applyPrincipledDiagonalNugget (EigenMatrix &K, Eigen::Index n_x, Eigen::Index d, double kappa_max, bool gradient_enhanced=true)
double computePrincipledNugget (Eigen::Index n_x, Eigen::Index d, double kappa_max, bool gradient_enhanced=true)
double principledKappaMaxDefault ()
Eigen::Vector3d priorParametersVector (const PriorBase &prior)
template<typename EigenObject>
bool reduce_laplace_factor_vectors_in_grid_order (std::vector< EigenObject > &factor_values, linalg::BackendContext &context)
double localTraceProduct (const EigenMatrix &A, const EigenMatrix &B)
Eigen::Vector3d priorParametersVector (const PriorBase &prior)
bool symmetrizeObservedInformation (Eigen::MatrixXd &H)
Eigen::VectorXd inlaClipToLogBox (const Eigen::VectorXd &theta, const Eigen::VectorXd &lower, const Eigen::VectorXd &upper)
void addConstantCovarianceBlock (ConstantCF *const_cov_fun, const Eigen::VectorXd &row_indices, const Eigen::VectorXd &col_indices, EigenMatrix &matrix)
template<typename EigenObject>
bool reduce_laplace_factor_vectors_in_grid_order (std::vector< EigenObject > &factor_values, linalg::BackendContext &context)
void writePredictionVectorToObservation (const Observation &query, const Eigen::VectorXd &values, Observation &out)
void addConstantCovarianceBlock (ConstantCF *const_cov_fun, const Eigen::VectorXd &row_indices, const Eigen::VectorXd &col_indices, EigenMatrix &matrix)
template<typename EigenObject>
bool reduce_laplace_factor_vectors_in_grid_order (std::vector< EigenObject > &factor_values, linalg::BackendContext &context)
bool symmetrizeObservedInformation (Eigen::MatrixXd &H)
void writeBMAOutput (const Eigen::VectorXd &flat, Index_t N_im, Index_t D, Observation &image1)
void writePredictionVectorToObservation (const Observation &query, const Eigen::VectorXd &values, Observation &out)

Variables

constexpr auto EigenDynamic = Eigen::Dynamic
constexpr auto EigenMatrixStorage = Eigen::StorageOptions::ColMajor
constexpr auto FieldMatrixStorage = Eigen::StorageOptions::RowMajor
constexpr ChartScalarKernel kDefaultChartScalarKernel
bool sexpat_local_oracle_active = false
double g_geom_build_seconds = 0.0
double g_max_cond_k = 0.0
double g_max_abs_alpha = 0.0
constexpr double kRFFEnergyNoiseFloor = 1e-6
 Energy-channel floor used by the production random-feature model.
constexpr double kRFFGradientNoiseFloor = 1e-4
 Gradient-channel floor used by the production random-feature model.
constexpr double kRFFForceConvergenceTolerance = 0.0514221
 Band force tolerance the random-feature error is not allowed to cross.
constexpr std::uint64_t kRFFValidationMemoryCapBytes
 Exact validation Gram, and the D-by-D normal matrix, stay under this.
constexpr int kRFFFeaturesAuto = -1
 Sentinel stored in integer feature-count fields for the automatic rule.

Detailed Description

Gaussian-process regression, kernels, priors, and the searches that run on the surrogate.

Typedef Documentation

◆ Coord

Definition at line 35 of file Macros.h.

◆ CutoffPairFeatures

Definition at line 90 of file PairCutoff.h.

◆ EigenMatrix

Initial value:
Eigen::Matrix<double, EigenDynamic, EigenDynamic, EigenMatrixStorage>

Definition at line 20 of file Macros.h.

◆ FieldMatrixd

Initial value:
Eigen::Matrix<double, EigenDynamic, EigenDynamic, FieldMatrixStorage>

Definition at line 25 of file Macros.h.

◆ FieldMatrixi

Initial value:
Eigen::Matrix<int, EigenDynamic, EigenDynamic, FieldMatrixStorage>

Definition at line 27 of file Macros.h.

◆ FieldMatrixIdx

Initial value:
Eigen::Matrix<Index_t, EigenDynamic, EigenDynamic, FieldMatrixStorage>

Definition at line 29 of file Macros.h.

◆ FieldMatrixU8

Initial value:
Eigen::Matrix<uint8_t, EigenDynamic, EigenDynamic, FieldMatrixStorage>

Definition at line 31 of file Macros.h.

◆ Index_t

using gpr::Index_t = uint32_t

Definition at line 17 of file Macros.h.

◆ KernelMatrixBuilder

Initial value:
std::function<EigenMatrix(
const std::vector<double>& lengthscales, double noise)>
Eigen::Matrix< double, EigenDynamic, EigenDynamic, EigenMatrixStorage > EigenMatrix
Definition Macros.h:20

Kernel matrix builder: given lengthscales and noise, return K_XX.

Definition at line 58 of file ARDGridSearch.h.

◆ RefusalAwareHessianAction

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

Hessian action that reports whether an exact child refused.

Definition at line 175 of file KernelOperator.h.

◆ RefusalAwareHessianPreparation

Initial value:
const Eigen::VectorXd&, bool& exact_refusal)>
std::function< bool( const Eigen::VectorXd &, Eigen::VectorXd &, bool &exact_refusal)> RefusalAwareHessianAction
Hessian action that reports whether an exact child refused.

Query preparation that reports whether an exact child refused.

Definition at line 178 of file KernelOperator.h.

◆ vector3_reg

using gpr::vector3_reg = Eigen::Vector3d

Definition at line 36 of file Macros.h.

Enumeration Type Documentation

◆ BorderedSchurSign

enum class gpr::BorderedSchurSign
strong

ClampNegative treats the inputs as a PSD bordered covariance: a negative lower endpoint becomes 0 when the upper endpoint is nonnegative, and a negative upper endpoint is refused. PreserveSigned reports the signed Schur value, including a negative one.

Enumerator
ClampNegative 
PreserveSigned 

Definition at line 81 of file StableBasis.h.

◆ ChartScalarKernel

enum class gpr::ChartScalarKernel
strong

Chart scalar kernel. SquaredExponential is the production default. Matern52 is off unless a caller passes it explicitly.

Enumerator
SquaredExponential 
Matern52 

Definition at line 17 of file Matern52.h.

◆ GPModelProfile

enum class gpr::GPModelProfile : uint8_t
strong

Gaussian-process model profiles.

A profile bundles kernel-prior, fitting, and target-frame settings. CHEMGP and GPRD_ZBL use the same classic model path; their distinct values preserve configuration compatibility. Search algorithms and benchmark datasets are configured independently.

CHEMGP: joint energy-force inverse-distance GP with raw targets, NLML/SCG defaults and Sexpat priors including log-space Jacobians. GPRD_ZBL: the same classic settings, named for the dimer reference. Explicit CLI fitting choices take precedence over profile defaults. The ZBL prior mean is independent. Attached composite kernels stay active and use exact covariance factorization. EXTENDED: solver, objective, normalization and prior choices stay under their existing independent controls.

Enumerator
CHEMGP 
GPRD_ZBL 
EXTENDED 

Definition at line 201 of file Structures.h.

◆ HyperparameterObjectiveMode

Enumerator
NLML 
LOO 
LOCAL_LOO 

Definition at line 70 of file Enums.h.

◆ HyperparameterOptimizationMode

Enumerator
SCG 
INLA 
MAP_LBFGS 
RGMIN_SCG 
RGMIN_OPT 

Definition at line 56 of file Enums.h.

◆ MapPriorWeightMode

enum class gpr::MapPriorWeightMode : uint8_t
strong

Weighting of weakly-informative MAP prior terms vs the barrier anneal. Annealed (default): prior weight = min(barrier_strength, 0.5). Full: prior weight identically 1.0; barrier terms still use annealed strength.

Enumerator
Annealed 
Full 

Definition at line 100 of file Structures.h.

◆ PriorMeanStatistic

enum class gpr::PriorMeanStatistic
strong

Gaussian Process Regression algorithm.

Which statistic of the residual training energies is the constant prior mean the posterior reverts to away from the data.

Enumerator
Mean 
Maximum 

Definition at line 322 of file GaussianProcessRegression.h.

◆ ScgCurvatureMode

enum class gpr::ScgCurvatureMode
strong

Selects how SCG computes the directional curvature term.

EXACT uses the closed-form analytic curvature derived from the squared exponential covariance + Cholesky factor. FINITE_DIFFERENCE uses a sigma-perturbation probe. NLML_HESSIAN_VECTOR (opt-in) takes the curvature of SCG, of the length-scale tie screen and of the stationarity check from the exact Hessian-vector product of the Gaussian negative log marginal likelihood. Where that product does not exist or fails, each takes the FINITE_DIFFERENCE path, with a log line.

Enumerator
EXACT 
FINITE_DIFFERENCE 
NLML_HESSIAN_VECTOR 

Definition at line 161 of file Structures.h.

◆ UncertaintyMode

enum class gpr::UncertaintyMode
strong

Selector for the uncertainty-quantification path consumed by AcquisitionStrategy / AtomicDimer / GPNEB. MAP is the default point-estimate variance from calculateVariance; LAPLACE routes through a Rue et al. 2009 CCD mixture over the hyperparameter posterior; LAPLACE_SLICE replaces the CCD quadrature with Neal 2003 doubling slice sampling on the same NLML target (asymptotically exact instead of quadrature-on-Laplace-ellipsoid; per-fit cost is M ~ 100 Cholesky bursts but per-predict cost is O(M * n^2) with no new Cholesky); BMA uses BayesianModelAveraging's uniform grid (for reference timing only – rarely used in production).

Enumerator
MAP 
BMA 
LAPLACE 
EB 
SVGD 
LAPLACE_SLICE 

Definition at line 177 of file Structures.h.

Function Documentation

◆ addConstantCovarianceBlock() [1/4]

void gpr::detail::addConstantCovarianceBlock ( ConstantCF * const_cov_fun,
const Eigen::VectorXd & row_indices,
const Eigen::VectorXd & col_indices,
EigenMatrix & matrix )
inline

Definition at line 67 of file Helpers.h.

71{
72 if (const_cov_fun == nullptr || matrix.size() == 0) return;
73 const double const_sigma2 = const_cov_fun->getConstSigma2();
74 if (const_sigma2 == 0.0) return;
75
76 const Eigen::Index row_block = leadingDerivativeBlockSize(row_indices, 0.0);
77 const Eigen::Index col_block = leadingDerivativeBlockSize(col_indices, 0.0);
78 if (row_block <= 0 || col_block <= 0 || row_block > matrix.rows() ||
79 col_block > matrix.cols()) {
80 return;
81 }
82 matrix.topLeftCorner(row_block, col_block).array() += const_sigma2;
83}
double getConstSigma2()

◆ addConstantCovarianceBlock() [2/4]

void gpr::detail::addConstantCovarianceBlock ( ConstantCF * const_cov_fun,
const Eigen::VectorXd & row_indices,
const Eigen::VectorXd & col_indices,
EigenMatrix & matrix )
inline

Definition at line 67 of file Helpers.h.

71{
72 if (const_cov_fun == nullptr || matrix.size() == 0) return;
73 const double const_sigma2 = const_cov_fun->getConstSigma2();
74 if (const_sigma2 == 0.0) return;
75
76 const Eigen::Index row_block = leadingDerivativeBlockSize(row_indices, 0.0);
77 const Eigen::Index col_block = leadingDerivativeBlockSize(col_indices, 0.0);
78 if (row_block <= 0 || col_block <= 0 || row_block > matrix.rows() ||
79 col_block > matrix.cols()) {
80 return;
81 }
82 matrix.topLeftCorner(row_block, col_block).array() += const_sigma2;
83}

◆ addConstantCovarianceBlock() [3/4]

void gpr::detail::addConstantCovarianceBlock ( ConstantCF * const_cov_fun,
const Eigen::VectorXd & row_indices,
const Eigen::VectorXd & col_indices,
EigenMatrix & matrix )
inline

Definition at line 67 of file Helpers.h.

71{
72 if (const_cov_fun == nullptr || matrix.size() == 0) return;
73 const double const_sigma2 = const_cov_fun->getConstSigma2();
74 if (const_sigma2 == 0.0) return;
75
76 const Eigen::Index row_block = leadingDerivativeBlockSize(row_indices, 0.0);
77 const Eigen::Index col_block = leadingDerivativeBlockSize(col_indices, 0.0);
78 if (row_block <= 0 || col_block <= 0 || row_block > matrix.rows() ||
79 col_block > matrix.cols()) {
80 return;
81 }
82 matrix.topLeftCorner(row_block, col_block).array() += const_sigma2;
83}

◆ addConstantCovarianceBlock() [4/4]

void gpr::detail::addConstantCovarianceBlock ( ConstantCF * const_cov_fun,
const Eigen::VectorXd & row_indices,
const Eigen::VectorXd & col_indices,
EigenMatrix & matrix )
inline

Definition at line 67 of file Helpers.h.

71{
72 if (const_cov_fun == nullptr || matrix.size() == 0) return;
73 const double const_sigma2 = const_cov_fun->getConstSigma2();
74 if (const_sigma2 == 0.0) return;
75
76 const Eigen::Index row_block = leadingDerivativeBlockSize(row_indices, 0.0);
77 const Eigen::Index col_block = leadingDerivativeBlockSize(col_indices, 0.0);
78 if (row_block <= 0 || col_block <= 0 || row_block > matrix.rows() ||
79 col_block > matrix.cols()) {
80 return;
81 }
82 matrix.topLeftCorner(row_block, col_block).array() += const_sigma2;
83}

◆ applyCanonicalReadconDimerDefaults()

void gpr::applyCanonicalReadconDimerDefaults ( InputParameters & parameters,
const CanonicalDimerDefaultOptions & options = {} )

Apply the canonical readcon dimer defaults to parameters.

Also installs the published Student-t prior parameters (mu = 0, nu = 20, s2 = 1). initialize() copies this triple onto the Student-t magnitude, Gaussian length-scale, and log-normal priors; data-bearing setHyperparameters() later overwrites Student-t s2 with target_variance and Gaussian s2 with seed_length_scale_^2.

Definition at line 34 of file ParameterDefaults.cpp.

36{
37 parameters.dimer_sep.value = kDimerSeparation;
38 parameters.method_rot.value = "LBFGS_alg";
39 parameters.method_trans.value = "LBFGS_alg";
40 parameters.param_trans.value[0] = kTranslationStep;
41 parameters.param_trans.value[1] = kTranslationMaxStep;
42 parameters.T_dimer.value = kDimerForceTolerance;
43 parameters.T_anglerot_init.value = kInitialRotationAngleTolerance;
44 parameters.num_iter_initrot.value = kInitialRotationIterations;
45 parameters.T_anglerot_gp.value = kGpRotationAngleTolerance;
46 parameters.divisor_T_dimer_gp.value = kGpRotationToleranceDivisor;
47 parameters.disp_max.value = kMiddlePointMaxDisplacement;
48 parameters.ratio_at_limit.value = kInteratomicDistanceRatioLimit;
49 parameters.num_bigiter.value = kDimerOuterIterations;
50 parameters.num_iter.value = kDimerInnerIterations;
51 parameters.islarge_num_iter.value = kLargeIterationPolicy;
52 parameters.dist_sp.value[0] = kSpecialDistanceStep;
53 parameters.report_level.value = options.report_level;
54 parameters.actdist_fro.value = options.actdist_fro;
55 parameters.evict_frozen.value = options.evict_frozen;
56 parameters.nn_frozen.value = options.nn_frozen;
57 parameters.nn_auto.value = options.nn_auto;
60 parameters.fps_history.value = options.fps_history;
61 parameters.rot_opt.value = "lbfgs";
62 parameters.use_prune.value = options.use_prune;
63 parameters.start_prune_at.value = kPruneWarmup;
64 parameters.nprune_vals.value = kPruneDropCount;
65 parameters.prune_threshold.value = kPruneThreshold;
67 kRotationRemovalProjectionThreshold;
68 // Published Student-t prior parameters (mu = 0, nu = 20, s2 = 1).
69 // initialize() copies this triple onto the Student-t magnitude, Gaussian
70 // length-scale, and log-normal priors as their initial values;
71 // data-bearing setHyperparameters() then replaces Student-t s2 with
72 // target_variance and Gaussian s2 with seed_length_scale_^2. Zero is not
73 // a sentinel; the densities divide by nu and s2.
74 parameters.prior_mu.value = 0.0;
75 parameters.prior_nu.value = kPublishedPriorNu;
76 parameters.prior_s2.value = kPublishedPriorS2;
77}
KeyValuePair< double[2]> param_trans
Definition Structures.h:440
KeyValuePair< double > T_anglerot_gp
Definition Structures.h:484
KeyValuePair< double > prior_s2
Definition Structures.h:650
KeyValuePair< DistanceMetricType > es_dist_metric
Definition Structures.h:652
KeyValuePair< double > dimer_sep
Definition Structures.h:425
KeyValuePair< int > start_prune_at
Definition Structures.h:571
KeyValuePair< int > islarge_num_iter
Definition Structures.h:544
KeyValuePair< int > fps_history
Definition Structures.h:665
KeyValuePair< double > prior_nu
Definition Structures.h:649
KeyValuePair< int > report_level
Definition Structures.h:673
KeyValuePair< double > rotation_removal_projection_threshold
Definition Structures.h:667
KeyValuePair< int > nn_frozen
Definition Structures.h:381
KeyValuePair< double > T_anglerot_init
Definition Structures.h:474
KeyValuePair< double > ratio_at_limit
Definition Structures.h:512
KeyValuePair< std::string > method_trans
Definition Structures.h:435
KeyValuePair< std::string > rot_opt
Definition Structures.h:670
KeyValuePair< double > prune_threshold
Definition Structures.h:581
KeyValuePair< DistanceMetricType > fps_metric
Definition Structures.h:663
KeyValuePair< int > nprune_vals
Definition Structures.h:576
KeyValuePair< int > nn_auto
Definition Structures.h:382
KeyValuePair< double > actdist_fro
Definition Structures.h:379
KeyValuePair< std::string > method_rot
Definition Structures.h:430
KeyValuePair< bool > use_prune
Definition Structures.h:562
KeyValuePair< int > divisor_T_dimer_gp
Definition Structures.h:498
KeyValuePair< int > num_iter
Definition Structures.h:537
KeyValuePair< int > num_iter_initrot
Definition Structures.h:479
KeyValuePair< double > disp_max
Definition Structures.h:505
KeyValuePair< double[4]> dist_sp
Definition Structures.h:374
KeyValuePair< double > prior_mu
Definition Structures.h:648
KeyValuePair< int > num_bigiter
Definition Structures.h:532
KeyValuePair< double > T_dimer
Definition Structures.h:453
KeyValuePair< int > evict_frozen
Definition Structures.h:380

◆ applyGprdDimerDefaults()

void gpr::applyGprdDimerDefaults ( InputParameters & parameters,
const CanonicalDimerDefaultOptions & options = gprdUnflaggedDimerOptions() )

The parameter block gprd installs before it applies flags: the canonical readcon dimer defaults, then the GP hyperparameter block in main. gpr_dimer_search starts from the same block.

Definition at line 87 of file ParameterDefaults.cpp.

89{
90 applyCanonicalReadconDimerDefaults(parameters, options);
91 parameters.gp_sigma2.value = 1e-4;
92 // Principled bounded nugget. Outputs are standardized to unit signal
93 // variance, so 1e-4 bounds cond(K). sigma2 is the separate noise
94 // channel; it is not gp_sigma2.
95 parameters.jitter_sigma2.value = 1e-4;
96 parameters.sigma2.value = 1e-4;
97 parameters.magnSigma2.value = 0.0;
98 parameters.constSigma2.value = 0.0;
99 // Restate the canonical prior after the GP block so this helper still
100 // publishes nu = 20, s2 = 1 when a caller zeros the struct first.
101 parameters.prior_mu.value = 0;
102 parameters.prior_nu.value = kPublishedPriorNu;
103 parameters.prior_s2.value = kPublishedPriorS2;
104 parameters.optimization_alg.value = "SCG_opt";
105 parameters.max_iter.value = 400;
106 parameters.tolerance_func.value = 1e-3;
107 parameters.tolerance_sol.value = 1e-3;
108 parameters.lambda_limit.value = 1e16;
109 parameters.lambda.value = 100.0;
110 parameters.check_derivative.value = "false";
111}
void applyCanonicalReadconDimerDefaults(InputParameters &parameters, const CanonicalDimerDefaultOptions &options)
Apply the canonical readcon dimer defaults to parameters.
KeyValuePair< int > max_iter
Definition Structures.h:674
KeyValuePair< std::string > optimization_alg
Definition Structures.h:614
KeyValuePair< double > lambda
Definition Structures.h:678
KeyValuePair< double > jitter_sigma2
Definition Structures.h:613
KeyValuePair< double > constSigma2
Definition Structures.h:618
KeyValuePair< double > lambda_limit
Definition Structures.h:677
KeyValuePair< double > tolerance_func
Definition Structures.h:675
KeyValuePair< std::string > check_derivative
Definition Structures.h:672
KeyValuePair< double > tolerance_sol
Definition Structures.h:676
KeyValuePair< double > sigma2
Definition Structures.h:616
KeyValuePair< double > magnSigma2
Definition Structures.h:617
KeyValuePair< double > gp_sigma2
Definition Structures.h:612

◆ applyPrincipledDiagonalNugget()

double gpr::detail::applyPrincipledDiagonalNugget ( EigenMatrix & K,
Eigen::Index n_x,
Eigen::Index d,
double kappa_max,
bool gradient_enhanced = true )
inline

Definition at line 296 of file Helpers.h.

299{
300 if (K.rows() != K.cols() || K.rows() == 0) return 0.0;
301 const double eta =
302 computePrincipledNugget(n_x, d, kappa_max, gradient_enhanced);
303 if (!(eta > 0.0)) return 0.0;
304 for (Eigen::Index i = 0; i < K.rows(); ++i)
305 K(i, i) += eta * K(i, i);
306 return eta;
307}

◆ applyStableBasisStatisticalInverse()

Eigen::VectorXd gpr::applyStableBasisStatisticalInverse ( const StableBasisND & basis,
const Eigen::VectorXd & rhs,
double noise )

Definition at line 82 of file Variance.cpp.

85{
86 const auto& psi = basis.leftSingularVectors();
87 const auto& singular = basis.singularValues();
88 const double sigma2 = basis.conditionFlooredNoise(noise);
89 if (psi.rows() != rhs.size() || psi.cols() != singular.size() ||
90 !(sigma2 > 0.0) || !std::isfinite(sigma2))
91 return {};
92 const Eigen::VectorXd z = psi.transpose() * rhs;
93 const Eigen::VectorXd residual = rhs - psi * z;
94 Eigen::VectorXd action =
95 psi * (z.array() / (singular.array().square() + sigma2)).matrix();
96 const double weight = basis.covarianceComplementWeight(sigma2);
97 if (weight > 0.0)
98 action.noalias() +=
99 weight * (residual - psi * (psi.transpose() * residual));
100 return action;
101}
@ z
Definition Enums.h:28
double covarianceComplementWeight(double sigma2) const noexcept
const Eigen::MatrixXd & leftSingularVectors() const
double conditionFlooredNoise(double sigma2) const
const Eigen::VectorXd & singularValues() const

◆ arrowheadEigenpairs()

bool gpr::arrowheadEigenpairs ( const Eigen::Ref< const Eigen::VectorXd > & diagonal,
const Eigen::Ref< const Eigen::VectorXd > & spike,
double corner,
Eigen::VectorXd & evals,
Eigen::MatrixXd & evecs )
inlinenodiscard

Eigenpairs of [diag(diagonal), spike; spike^T, corner], ascending. False when a pole gap is inside the symmetric backward error: the caller then uses the full eigensolver, whose basis is the one the search already runs.

Definition at line 31 of file ArrowheadSpectrum.h.

35{
36 const Eigen::Index n = diagonal.size();
37 if (n <= 0 || spike.size() != n || !diagonal.allFinite() ||
38 !spike.allFinite() || !std::isfinite(corner))
39 return false;
40
41 double scale = std::abs(corner);
42 for (Eigen::Index i = 0; i < n; ++i)
43 scale = std::max(scale, std::abs(diagonal(i)));
44 scale = std::max(scale, spike.cwiseAbs().maxCoeff());
45 const double gap = linalg::symmetricBackwardError(n + 1, scale);
46
47 std::vector<Eigen::Index> order(static_cast<std::size_t>(n));
48 for (Eigen::Index i = 0; i < n; ++i)
49 order[static_cast<std::size_t>(i)] = i;
50 std::sort(order.begin(), order.end(), [&](Eigen::Index a, Eigen::Index b) {
51 return diagonal(a) < diagonal(b);
52 });
53 for (std::size_t i = 1; i < order.size(); ++i) {
54 if (diagonal(order[i]) - diagonal(order[i - 1]) <= gap) return false;
55 }
56
57 Eigen::VectorXd d(n);
58 Eigen::VectorXd u(n);
59 std::vector<Eigen::Index> active;
60 active.reserve(static_cast<std::size_t>(n));
61 const double spike_scale = std::max(spike.cwiseAbs().maxCoeff(), 1.0);
62 for (Eigen::Index i = 0; i < n; ++i) {
63 d(i) = diagonal(order[static_cast<std::size_t>(i)]);
64 u(i) = spike(order[static_cast<std::size_t>(i)]);
65 if (std::abs(u(i)) > gap * spike_scale) active.push_back(i);
66 }
67
68 const auto secular = [&](double lambda) {
69 long double sum = static_cast<long double>(corner - lambda);
70 for (const Eigen::Index i: active) {
71 const long double denom = static_cast<long double>(d(i)) -
72 static_cast<long double>(lambda);
73 sum -= static_cast<long double>(u(i)) *
74 static_cast<long double>(u(i)) / denom;
75 }
76 return static_cast<double>(sum);
77 };
78
79 const double reach = spike.norm() + std::abs(corner) + scale + 1.0;
80 std::vector<std::pair<double, double>> brackets;
81 brackets.reserve(static_cast<std::size_t>(active.size() + 2));
82 if (!active.empty()) {
83 brackets.emplace_back(d(active.front()) - reach, d(active.front()));
84 for (std::size_t i = 1; i < active.size(); ++i)
85 brackets.emplace_back(d(active[i - 1]), d(active[i]));
86 brackets.emplace_back(d(active.back()), d(active.back()) + reach);
87 } else {
88 brackets.emplace_back(corner - reach, corner + reach);
89 }
90
91 const auto isolate = [&](double left, double right, double& root) {
92 const double width = right - left;
93 if (!(width > gap)) return false;
94 const double pad =
95 std::max(gap, width * std::numeric_limits<double>::epsilon());
96 double lo = left + pad;
97 double hi = right - pad;
98 if (!(lo < hi)) return false;
99 double flo = secular(lo);
100 double fhi = secular(hi);
101 if (!std::isfinite(flo) || !std::isfinite(fhi) || flo * fhi > 0.0)
102 return false;
103 for (int iter = 0; iter < 80 && hi - lo > gap; ++iter) {
104 const double mid = 0.5 * (lo + hi);
105 const double fmid = secular(mid);
106 if (!std::isfinite(fmid)) return false;
107 if (flo * fmid <= 0.0) {
108 hi = mid;
109 fhi = fmid;
110 } else {
111 lo = mid;
112 flo = fmid;
113 }
114 }
115 root = 0.5 * (lo + hi);
116 return std::isfinite(root);
117 };
118
119 std::vector<double> roots;
120 roots.reserve(brackets.size());
121 for (const auto& bracket: brackets) {
122 double root = 0.0;
123 if (!isolate(bracket.first, bracket.second, root)) return false;
124 roots.push_back(root);
125 }
126 if (static_cast<Eigen::Index>(
127 roots.size() + (n - static_cast<Eigen::Index>(active.size()))) !=
128 n + 1)
129 return false;
130
131 evals.resize(n + 1);
132 evecs = Eigen::MatrixXd::Zero(n + 1, n + 1);
133 Eigen::Index col = 0;
134 for (Eigen::Index i = 0; i < n; ++i) {
135 if (std::abs(u(i)) > gap * spike_scale) continue;
136 evals(col) = d(i);
137 evecs(i, col) = 1.0;
138 ++col;
139 }
140 for (const double lambda: roots) {
141 evals(col) = lambda;
142 double norm_sq = 1.0;
143 for (const Eigen::Index i: active) {
144 // (D - λ I) v_head + spike * v_corner = 0 with v_corner = 1.
145 const double component = u(i) / (lambda - d(i));
146 evecs(i, col) = component;
147 norm_sq += component * component;
148 }
149 evecs(n, col) = 1.0;
150 evecs.col(col) /= std::sqrt(norm_sq);
151 ++col;
152 }
153 if (col != n + 1) return false;
154
155 // The secular vectors are in the sorted-diagonal order. Permute the
156 // leading rows back to the caller's diagonal order; the new row stays.
157 Eigen::MatrixXd restored = evecs;
158 for (Eigen::Index i = 0; i < n; ++i)
159 restored.row(order[static_cast<std::size_t>(i)]) = evecs.row(i);
160 evecs = restored;
161 linalg::canonicalizeEigenpairs(evals, evecs);
162 return true;
163}
void canonicalizeEigenpairs(Eigen::Ref< Eigen::VectorXd > evals, Eigen::Ref< Eigen::MatrixXd > evecs)
evals has one entry per leading column of evecs. Both are rewritten.
double symmetricBackwardError(Eigen::Index n, double scale) noexcept

◆ assembleCollectively()

template<class Matrices, class Body>
void gpr::linalg::assembleCollectively ( const MpiContext & context,
Matrices & result,
const Body & body )

Assemble disjoint entries, propagate failures within the owning group, and replicate the tensors. The body joins its workers before returning; only the calling thread enters MPI collectives.

Definition at line 19 of file CollectiveAssembly.h.

21{
22 std::exception_ptr failure;
23 try {
24 body();
25 } catch (...) {
26 failure = std::current_exception();
27 }
28#if defined(GPR_HAVE_MPI) || defined(GPR_LINALG_SCALAPACK)
29 if (context.is_distributed()) {
30 int failed = failure ? 1 : 0;
31 if (MPI_Allreduce(MPI_IN_PLACE, &failed, 1, MPI_INT, MPI_MAX,
32 context.comm) != MPI_SUCCESS)
33 throw std::runtime_error("could not share assembly status");
34 if (failed && !failure)
35 throw std::runtime_error("assembly failed on another rank");
36 }
37#endif
38 if (failure) std::rethrow_exception(failure);
39 if (!context.is_distributed()) return;
40 constexpr Eigen::Index maximum = std::numeric_limits<int>::max();
41 for (auto& matrix: result)
42 for (Eigen::Index offset = 0; offset < matrix.size();) {
43 const int entries =
44 static_cast<int>(std::min(maximum, matrix.size() - offset));
45 disjoint_sum_bcast(matrix.data() + offset, entries, context);
46 offset += entries;
47 }
48}
void disjoint_sum_bcast(double *data, int count, const MpiContext &context)

◆ buildCrossBlockDerivativesFactored()

bool gpr::buildCrossBlockDerivativesFactored ( const FactoredTrainingGeometry & factors,
Index_t block_n,
Index_t block_m,
uint8_t derivative_options,
SexpatCF::CrossBlockGeometry & out )
nodiscard

Rebuild one block's d1/d2/d12 fields from the factors, in the layout and sign convention of SexpatCF::buildCrossBlockDerivativesOnly.

Definition at line 141 of file CovarianceAssembly.cpp.

145{
147 out.derivative_options = derivative_options;
148 if (!factors.valid || derivative_options == 0) {
149 out.valid = derivative_options == 0;
150 return out.valid;
151 }
152 // Block dimension values count the energy block as 0; coordinate d of
153 // the Jacobian is dimension value d + 1.
154 const Index_t dn = block_n - 1;
155 const Index_t dm = block_m - 1;
156 const Index_t n_dims = static_cast<Index_t>(factors.J.size());
157 const bool want_d2 =
158 (derivative_options & OptionsForGradCalculation::D2) != 0;
159 const bool want_d12 =
160 (derivative_options & OptionsForGradCalculation::D12) != 0;
161 if (dn < 0 || dn >= n_dims ||
162 ((want_d2 || want_d12) && (dm < 0 || dm >= n_dims))) {
163 return false;
164 }
165 const EigenMatrix& Jn = factors.J[static_cast<std::size_t>(dn)];
166 const EigenMatrix* Jm = (want_d2 || want_d12)
167 ? &factors.J[static_cast<std::size_t>(dm)]
168 : nullptr;
169 const Index_t n_conf = factors.Q.rows();
170 const Eigen::VectorXd ones = Eigen::VectorXd::Ones(n_conf);
171 out.d1.assign(static_cast<std::size_t>(factors.n_pt), FieldMatrixd());
172 if (want_d2)
173 out.d2.assign(static_cast<std::size_t>(factors.n_pt), FieldMatrixd());
174 if (want_d12)
175 out.d12.assign(static_cast<std::size_t>(factors.n_pt), FieldMatrixd());
176 for (Index_t pt = 0; pt < factors.n_pt; ++pt) {
177 const auto& F = factors.features_by_pt[static_cast<std::size_t>(pt)];
178 const Index_t nf = static_cast<Index_t>(F.size());
179 EigenMatrix Qf(n_conf, nf), Jnf(n_conf, nf),
180 Jmf(n_conf, want_d2 || want_d12 ? nf : 0);
181 for (Index_t k = 0; k < nf; ++k) {
182 Qf.col(k) = factors.Q.col(F[static_cast<std::size_t>(k)]);
183 Jnf.col(k) = Jn.col(F[static_cast<std::size_t>(k)]);
184 if (Jm) Jmf.col(k) = Jm->col(F[static_cast<std::size_t>(k)]);
185 }
186 const Eigen::VectorXd cn = (Jnf.array() * Qf.array()).rowwise().sum();
187 // Convention of buildCrossBlockDerivativesOnly (measured against
188 // the walked blocks in FactoredBlockDerivativesMatchTheWalkedGeometry):
189 // the stored fields are twice the pair-type derivatives, d1 and d2
190 // (d1, d2 with the sign of the derivative, d12 with that sign too).
191 out.d1[static_cast<std::size_t>(pt)] =
192 4.0 * cn * ones.transpose() - 4.0 * Jnf * Qf.transpose();
193 if (want_d2) {
194 const Eigen::VectorXd cm =
195 (Jmf.array() * Qf.array()).rowwise().sum();
196 out.d2[static_cast<std::size_t>(pt)] =
197 4.0 * ones * cm.transpose() - 4.0 * Qf * Jmf.transpose();
198 }
199 if (want_d12) {
200 out.d12[static_cast<std::size_t>(pt)] =
201 -4.0 * Jnf * Jmf.transpose();
202 }
203 }
204 out.valid = true;
205 return true;
206}
@ D12
Definition Enums.h:21
@ D2
Definition Enums.h:20
eon_relax_band_t eon_relax_surface_fn void eon_relax_outcome_t * out
uint32_t Index_t
Definition Macros.h:17
Eigen::Matrix< double, EigenDynamic, EigenDynamic, FieldMatrixStorage > FieldMatrixd
Definition Macros.h:25
std::vector< std::vector< Index_t > > features_by_pt
std::vector< EigenMatrix > J
per dimension, n_conf x d_feat

◆ buildFactoredTrainingGeometry()

bool gpr::buildFactoredTrainingGeometry ( const AtomsConfiguration & conf_info,
const FieldMatrixd & x_loc,
FactoredTrainingGeometry & out,
double far_field_radius = 0.0 )
nodiscard

Definition at line 94 of file CovarianceAssembly.cpp.

98{
100 const Index_t n_conf = static_cast<Index_t>(x_loc.rows());
101 const Index_t n_coord =
102 3 * static_cast<Index_t>(conf_info.atoms_mov.type.size());
103 if (n_conf == 0 || n_coord == 0 || x_loc.cols() < n_coord ||
104 conf_info.n_pt == 0)
105 return false;
106 const std::vector<int> fpt = InverseDistanceDescriptor::featurePairtypes(
107 conf_info, far_field_radius);
108 const Index_t d_feat = static_cast<Index_t>(fpt.size());
109 if (d_feat <= 0) return false;
110 out.n_pt = conf_info.n_pt;
111 out.features_by_pt.assign(static_cast<std::size_t>(conf_info.n_pt), {});
112 for (Index_t f = 0; f < d_feat; ++f) {
113 const int pt = fpt[static_cast<std::size_t>(f)];
114 if (pt < 0 || pt >= conf_info.n_pt) return false;
115 out.features_by_pt[static_cast<std::size_t>(pt)].push_back(f);
116 }
117 out.Q.resize(n_conf, d_feat);
118 out.J.assign(static_cast<std::size_t>(n_coord),
119 EigenMatrix::Zero(n_conf, d_feat));
120 Eigen::VectorXd phi;
121 EigenMatrix J_phi;
122 for (Index_t i = 0; i < n_conf; ++i) {
123 Coord xi(1, n_coord);
124 xi.row(0) = x_loc.block(i, 0, 1, n_coord);
126 J_phi, far_field_radius);
127 if (phi.size() != d_feat || J_phi.rows() != d_feat ||
128 J_phi.cols() != n_coord || !phi.allFinite() || !J_phi.allFinite()) {
129 return false;
130 }
131 out.Q.row(i) = phi.transpose();
132 for (Index_t d = 0; d < n_coord; ++d) {
133 out.J[static_cast<std::size_t>(d)].row(i) =
134 J_phi.col(d).transpose();
135 }
136 }
137 out.valid = true;
138 return true;
139}
static std::vector< int > featurePairtypes(const AtomsConfiguration &conf_info)
Pairtype index for each feature.
static void computeWithJacobian(const Coord &x, const AtomsConfiguration &conf_info, Eigen::VectorXd &phi, EigenMatrix &J_phi)
Compute phi(x) and its Jacobian d(phi)/d(x).
FieldMatrixd Coord
Definition Macros.h:35
AtomsPositionAndType atoms_mov
Info on moving atoms.
Definition Structures.h:844

◆ buildObservationTiledPermutation()

StructuredPermutation gpr::buildObservationTiledPermutation ( const Eigen::VectorXd & ind_Ddim)
inline

Definition at line 184 of file PermutationUtils.h.

186{
188 const Index_t n = static_cast<Index_t>(ind_Ddim.size());
189 p.perm.reserve(n);
190 p.inv_perm.resize(n, -1);
191
192 if (n == 0) return p;
193
194 const detail::ObservationChannelLayout channels(ind_Ddim);
195 const Index_t n_blocks = static_cast<Index_t>(channels.channelCount());
196 const Index_t block_rows = static_cast<Index_t>(channels.rowsPerChannel());
197
198 // A tile contains one row from each stored channel. Unequal channel
199 // counts have no rectangular observation-tiled representation.
200 if (!channels.valid() || block_rows == 0) {
201 p.perm.clear();
202 p.inv_perm.assign(static_cast<size_t>(n), -1);
203 return p;
204 }
205
206 for (Index_t row = 0; row < block_rows; ++row) {
207 for (Index_t block = 0; block < n_blocks; ++block) {
208 p.perm.push_back(block * block_rows + row);
209 }
210 }
211
212 for (Index_t i = 0; i < n; ++i)
213 p.inv_perm[p.perm[i]] = i;
214
215 return p;
216}
std::vector< Index_t > inv_perm
std::vector< Index_t > perm

◆ buildStructuredPermutation()

StructuredPermutation gpr::buildStructuredPermutation ( const Eigen::VectorXd & ind_Ddim)
inline

Definition at line 155 of file PermutationUtils.h.

157{
159 const Index_t n = static_cast<Index_t>(ind_Ddim.size());
160 p.perm.reserve(n);
161 p.inv_perm.resize(n, -1);
162
163 std::vector<Index_t> groups;
164 groups.reserve(n);
165 for (Index_t i = 0; i < n; ++i) {
166 const Index_t value = static_cast<Index_t>(ind_Ddim(i));
167 if (std::find(groups.begin(), groups.end(), value) == groups.end())
168 groups.push_back(value);
169 }
170 std::sort(groups.begin(), groups.end());
171
172 for (Index_t group: groups) {
173 for (Index_t i = 0; i < n; ++i) {
174 if (static_cast<Index_t>(ind_Ddim(i)) == group) p.perm.push_back(i);
175 }
176 }
177
178 for (Index_t i = 0; i < n; ++i)
179 p.inv_perm[p.perm[i]] = i;
180
181 return p;
182}

◆ certifyFinalSaddle()

SaddleCertificate gpr::certifyFinalSaddle ( double true_pes_saddle_force,
double conv_tol,
const std::vector< double > & per_image_variance,
double variance_envelope )

Combined force and variance criterion for callers that request it. The variance envelope is an optional exploration condition. A physical saddle additionally requires an independent assessment of its Hessian index; neither this helper nor a trust radius establishes that index.

Definition at line 91 of file ScaleFreeTrustRegion.cpp.

94{
96 cert.force_ok = std::isfinite(true_pes_saddle_force) &&
97 true_pes_saddle_force < conv_tol;
98
99 bool var_ok = !per_image_variance.empty();
100 for (const double v: per_image_variance) {
101 const double vv =
102 std::isfinite(v) ? std::max(0.0, v) : variance_envelope + 1.0;
103 if (vv > variance_envelope) {
104 var_ok = false;
105 break;
106 }
107 }
108 cert.variance_ok = var_ok;
109 cert.certified = cert.force_ok && cert.variance_ok;
110 return cert;
111}
Final-saddle certificate, split from the exploration radius.
bool certified
force_ok && variance_ok
bool variance_ok
all-image posterior var <= envelope
bool force_ok
true-PES saddle force < conv_tol

◆ collectiveWallClockLimitReached() [1/2]

bool gpr::collectiveWallClockLimitReached ( const std::shared_ptr< const WallClockLimit > & limit)
inline

The oracle/search process group, with a local fallback outside MPI.

Definition at line 103 of file PhaseTimers.h.

105{
106 if (!limit || !limit->enabled()) return false;
107#if defined(GPR_HAVE_MPI) || defined(GPR_LINALG_SCALAPACK)
108 int initialized = 0, finalized = 0;
109 MPI_Initialized(&initialized);
110 MPI_Finalized(&finalized);
111 if (initialized && !finalized)
113 linalg::MpiContext::world());
114#endif
115 return limit->reached();
116}
bool collectiveWallClockLimitReached(const std::shared_ptr< const WallClockLimit > &limit, const linalg::MpiContext &context)
Definition PhaseTimers.h:81

◆ collectiveWallClockLimitReached() [2/2]

bool gpr::collectiveWallClockLimitReached ( const std::shared_ptr< const WallClockLimit > & limit,
const linalg::MpiContext & context )
inline

Agree at a shared phase boundary before entering further collectives. Rank-local oracle callbacks use requireWallClock and agree their outcome through the oracle batch protocol instead.

Definition at line 81 of file PhaseTimers.h.

84{
85 if (!limit || !limit->enabled()) return false;
86 const bool reached = limit->reached();
87#if defined(GPR_HAVE_MPI) || defined(GPR_LINALG_SCALAPACK)
88 if (context.is_distributed()) {
89 const int local = reached ? 1 : 0;
90 int global = 0;
91 if (MPI_Allreduce(&local, &global, 1, MPI_INT, MPI_MAX, context.comm) !=
92 MPI_SUCCESS)
93 throw std::runtime_error("could not agree on wall-clock limit");
94 return global != 0;
95 }
96#else
97 (void)context;
98#endif
99 return reached;
100}
bool is_distributed() const noexcept
Definition MpiContext.h:67

◆ computePrincipledNugget()

double gpr::detail::computePrincipledNugget ( Eigen::Index n_x,
Eigen::Index d,
double kappa_max,
bool gradient_enhanced = true )
inline

Definition at line 255 of file Helpers.h.

258{
259 if (!(kappa_max > 1.0) || n_x <= 0) return 0.0;
260 const double N = gradient_enhanced
261 ? static_cast<double>(n_x) * static_cast<double>(d + 1)
262 : static_cast<double>(n_x);
263 return N / (kappa_max - 1.0);
264}

◆ conditionKernelMatrix() [1/2]

bool gpr::conditionKernelMatrix ( const Eigen::MatrixXd & joint,
const std::vector< Eigen::MatrixXd > & derivatives,
Eigen::Index anchor_rows,
Eigen::Index query_rows,
Eigen::Index dimensions,
const Eigen::VectorXd & anchor_noise,
Eigen::MatrixXd & covariance,
std::vector< Eigen::MatrixXd > & conditional_derivatives )
nodiscard

Project covariance and parameter derivatives using the same Schur complement. Joint rows are channel-major with anchors first in each channel. Anchor noise is fixed with respect to the fitted parameters.

Definition at line 309 of file ConditionedKernel.cpp.

315{
317 joint, derivatives, anchor_rows, query_rows, dimensions, anchor_noise,
318 covariance, conditional_derivatives, linalg::LocalExecutor{});
319}
bool conditionKernelMatrix(const Eigen::MatrixXd &joint, const std::vector< Eigen::MatrixXd > &derivatives, Eigen::Index anchor_rows, Eigen::Index query_rows, Eigen::Index dimensions, const Eigen::VectorXd &anchor_noise, Eigen::MatrixXd &covariance, std::vector< Eigen::MatrixXd > &conditional_derivatives)

◆ conditionKernelMatrix() [2/2]

bool gpr::conditionKernelMatrix ( const Eigen::MatrixXd & joint,
const std::vector< Eigen::MatrixXd > & derivatives,
Eigen::Index anchor_rows,
Eigen::Index query_rows,
Eigen::Index dimensions,
const Eigen::VectorXd & anchor_noise,
Eigen::MatrixXd & covariance,
std::vector< Eigen::MatrixXd > & conditional_derivatives,
const linalg::LocalExecutor & execution )
nodiscard

Definition at line 852 of file ConditionedKernel.cpp.

859{
861 if (!projection.prepare(joint, anchor_rows, query_rows, dimensions,
862 anchor_noise, covariance))
863 return false;
864 conditional_derivatives.clear();
865 for (const auto& derivative: derivatives)
866 if (derivative.rows() != joint.rows() ||
867 derivative.cols() != joint.cols() || !derivative.allFinite())
868 return false;
869 conditional_derivatives.resize(derivatives.size());
870 execution.forEach(derivatives.size(), [&](std::size_t index) {
871 conditional_derivatives[index] =
872 projection.derivative(derivatives[index]);
873 });
874 return true;
875}
bool prepare(const Eigen::MatrixXd &joint, Eigen::Index anchor_rows, Eigen::Index query_rows, Eigen::Index dimensions, const Eigen::VectorXd &anchor_noise, Eigen::MatrixXd &covariance, const std::shared_ptr< linalg::DistributedState > &execution={})
void forEach(std::size_t count, Operation &&operation, Grain grain=Grain::Fine) const

◆ consumerPublicLayout()

PublicLayoutBytes gpr::consumerPublicLayout ( )

◆ cutoffPairFeatures()

std::vector< CutoffPairFeatures > gpr::cutoffPairFeatures ( const Coord & positions,
const AtomsConfiguration & configuration )

Sorted pair features for each configuration; absent pairs are exact zeros.

Definition at line 19 of file PairCutoff.cpp.

21{
22 if (!(configuration.pair_cutoff > 0.0))
23 throw std::invalid_argument(
24 "sparse pair features require a finite cutoff");
25 return radialPairFeatures(positions, configuration);
26}
std::vector< CutoffPairFeatures > radialPairFeatures(const Coord &positions, const AtomsConfiguration &configuration)

◆ cutoffPairSquaredDistances()

std::vector< FieldMatrixd > gpr::cutoffPairSquaredDistances ( const Coord & left,
const Coord & right,
const AtomsConfiguration & configuration,
const FieldMatrixd & lengths )

Per-pairtype contributions to the Sexpat squared distance, 2 sum(delta^2/l^2).

Definition at line 184 of file PairCutoff.cpp.

187{
188 if (!(configuration.pair_cutoff > 0.0))
189 throw std::invalid_argument(
190 "sparse pair features require a finite cutoff");
191 return radialPairSquaredDistances(left, right, configuration, lengths, 0.0);
192}
std::vector< FieldMatrixd > radialPairSquaredDistances(const Coord &left, const Coord &right, const AtomsConfiguration &configuration, const FieldMatrixd &lengths, double far_radius)

◆ defaultDimerImage1EachPhase()

bool gpr::defaultDimerImage1EachPhase ( const bool use_hssvd,
const bool  )
nodiscardnoexcept

Definition at line 113 of file ParameterDefaults.cpp.

115{
116 // A companion force observation constrains the learned curvature even
117 // when the GP Hessian itself is evaluated analytically.
118 return use_hssvd;
119}

◆ excludeLibfabricBtlOnOneNode()

void gpr::excludeLibfabricBtlOnOneNode ( )
inlinenoexcept

Open MPI's libfabric BTL sleeps for one second when MPI_Finalize closes it (mca_btl_ofi_component_close), on every rank of every run that opened it. Ranks on one node exchange messages through the UCX or shared-memory transports and never use it, so a single-node launch leaves it out unless the caller chose the BTLs (OMPI_MCA_btl). Other MPI implementations ignore the variable.

Definition at line 42 of file MpiLifetime.h.

43{
44 if (std::getenv("OMPI_MCA_btl") != nullptr || !launchedOnOneNode()) return;
45 setenv("OMPI_MCA_btl", "^ofi", /*overwrite=*/0);
46}
bool launchedOnOneNode() noexcept
Definition MpiLifetime.h:24

◆ extendSymmetricSpectrum()

bool gpr::extendSymmetricSpectrum ( const Eigen::Ref< const Eigen::MatrixXd > & grown,
const Eigen::Ref< const Eigen::VectorXd > & diagonal,
const Eigen::Ref< const Eigen::MatrixXd > & basis,
Eigen::VectorXd & evals,
Eigen::MatrixXd & evecs )
inlinenodiscard

Eigenpairs of grown, whose leading principal submatrix has eigenpairs diagonal / basis (columns). Each new row is one arrowhead in that basis. False when any arrowhead is too clustered for the secular roots; the caller keeps the full eigensolver.

Definition at line 169 of file ArrowheadSpectrum.h.

174{
175 const Eigen::Index n0 = diagonal.size();
176 const Eigen::Index n = grown.rows();
177 if (n0 <= 0 || n <= n0 || grown.cols() != n || basis.rows() != n0 ||
178 basis.cols() != n0 || !grown.allFinite())
179 return false;
180
181 Eigen::VectorXd d = diagonal;
182 Eigen::MatrixXd q = basis;
183 for (Eigen::Index col = n0; col < n; ++col) {
184 const Eigen::Index m = q.rows();
185 const Eigen::VectorXd border = grown.col(col).head(m);
186 const Eigen::VectorXd spike = q.transpose() * border;
187 Eigen::VectorXd next_d;
188 Eigen::MatrixXd next_v;
189 if (!arrowheadEigenpairs(d, spike, grown(col, col), next_d, next_v))
190 return false;
191 Eigen::MatrixXd next_q(m + 1, m + 1);
192 next_q.topRows(m).noalias() = q * next_v.topRows(m);
193 next_q.row(m) = next_v.row(m);
194 q = std::move(next_q);
195 d = std::move(next_d);
196 }
197
198 const double scale = grown.cwiseAbs().maxCoeff();
199 // A dense matvec spreads the per-entry backward error across the
200 // vector. Roots inside this bound are the same eigenpairs a full
201 // symmetric solve is allowed to return.
202 const double residual_tol =
203 1024.0 * std::sqrt(static_cast<double>(n)) *
204 linalg::symmetricBackwardError(n, std::max(scale, 1.0));
205 for (Eigen::Index j = 0; j < d.size(); ++j) {
206 const double residual = (grown * q.col(j) - d(j) * q.col(j)).norm();
207 if (!std::isfinite(residual) || residual > residual_tol) return false;
208 }
209 evals = std::move(d);
210 evecs = std::move(q);
211 return true;
212}
bool arrowheadEigenpairs(const Eigen::Ref< const Eigen::VectorXd > &diagonal, const Eigen::Ref< const Eigen::VectorXd > &spike, double corner, Eigen::VectorXd &evals, Eigen::MatrixXd &evecs)

◆ findFMode()

Eigen::VectorXd gpr::findFMode ( const EigenMatrix & K,
const Eigen::VectorXd & y,
const ObservationLikelihood & ol,
int max_iter = 30,
double tol = 1e-8 )

Posterior mode f_mode = argmax_f [log p(y|f) + log N(f | 0, K)] via the Rasmussen-Williams safe Newton recursion (Algo 3.1).

Uses the B = I + W^{1/2} K W^{1/2} parameterisation that avoids inverting K directly. Converges in O(log(1/tol)) iterations on log-concave likelihoods when K is well-conditioned.

Parameters
KPrior covariance; pass the K_theta at the current hyperparameters (WITHOUT noise added; noise lives in W).
yObservations.
olObservation-likelihood contract (log-concave).
max_iterMax Newton steps; throws if exceeded without abs(Delta f) < tol * max(1, abs(f)).
tolRelative convergence tolerance.
Returns
Converged f_mode, same size as y.

Definition at line 12 of file ObservationLikelihood.cpp.

15{
16 const Eigen::Index n = K.rows();
17 if (K.cols() != n || y.size() != n) {
18 throw std::invalid_argument(
19 "findFMode: dimension mismatch between K and y");
20 }
21 Eigen::VectorXd f = Eigen::VectorXd::Zero(n); // R&W standard init
22
23 for (int iter = 0; iter < max_iter; ++iter) {
24 Eigen::VectorXd grad = ol.gradLogProb(y, f);
25 Eigen::VectorXd W_diag = ol.negHessDiag(y, f);
26 // Log-concavity guarantees W >= 0; clip negative rounding noise.
27 for (Eigen::Index i = 0; i < n; ++i) {
28 if (W_diag(i) < 0.0) W_diag(i) = 0.0;
29 }
30 const Eigen::VectorXd W_sqrt = W_diag.cwiseSqrt();
31
32 // B = I + W^{1/2} K W^{1/2}. Cholesky for numerical stability.
33 EigenMatrix B = EigenMatrix::Identity(n, n);
34 B += W_sqrt.asDiagonal() * K * W_sqrt.asDiagonal();
35 Eigen::LLT<EigenMatrix> llt(B);
36 if (llt.info() != Eigen::Success) {
37 throw std::runtime_error("findFMode: B Cholesky failed");
38 }
39
40 // R&W Algo 3.1: b = W f + grad; a = b - W^{1/2} B^{-1} W^{1/2} K b;
41 // f_new = K a.
42 const Eigen::VectorXd b_vec = W_diag.asDiagonal() * f + grad;
43 const Eigen::VectorXd Kb = K * b_vec;
44 const Eigen::VectorXd Binv_WKb = llt.solve(W_sqrt.asDiagonal() * Kb);
45 const Eigen::VectorXd a = b_vec - W_sqrt.asDiagonal() * Binv_WKb;
46 const Eigen::VectorXd f_new = K * a;
47
48 const double delta = (f_new - f).norm();
49 f = f_new;
50 if (delta < tol * std::max(1.0, f.norm())) return f;
51 }
52 throw std::runtime_error(
53 "findFMode: Newton did not converge within max_iter");
54}
@ y
Definition Enums.h:28
virtual Eigen::VectorXd negHessDiag(const Eigen::VectorXd &y, const Eigen::VectorXd &f) const =0
virtual Eigen::VectorXd gradLogProb(const Eigen::VectorXd &y, const Eigen::VectorXd &f) const =0
d/df log p(y|f); same size as f.

◆ forceDualNorm()

template<class Derived>
double gpr::forceDualNorm ( const Eigen::MatrixBase< Derived > & direction,
ConvergenceNormType norm )

Dual norm bounding the magnitude of direction dot force by ||direction||_* ||force||.

Definition at line 71 of file ForceNorm.h.

73{
74 if (direction.size() == 0 || !direction.allFinite())
75 return std::numeric_limits<double>::infinity();
76 switch (norm) {
78 return direction.cwiseAbs().sum();
80 if (direction.size() % 3 != 0)
81 return std::numeric_limits<double>::infinity();
82 double total = 0.0;
83 for (Eigen::Index i = 0; i < direction.size(); i += 3)
84 total += direction.template segment<3>(i).norm();
85 return total;
86 }
88 default:
89 return direction.norm();
90 }
91}

◆ forceNorm()

template<class Derived>
double gpr::forceNorm ( const Eigen::MatrixBase< Derived > & force,
ConvergenceNormType norm )

Force magnitude in the selected convergence norm.

Definition at line 45 of file ForceNorm.h.

47{
48 if (force.size() == 0 || !force.allFinite())
49 return std::numeric_limits<double>::infinity();
50 switch (norm) {
52 return force.cwiseAbs().maxCoeff();
54 if (force.size() % 3 != 0)
55 return std::numeric_limits<double>::infinity();
56 double maximum = 0.0;
57 for (Eigen::Index i = 0; i < force.size(); i += 3)
58 maximum =
59 std::max(maximum, force.template segment<3>(i).norm());
60 return maximum;
61 }
63 default:
64 return force.norm();
65 }
66}

◆ forceNormName()

std::string_view gpr::forceNormName ( std::optional< ConvergenceNormType > norm)
inline

Definition at line 29 of file ForceNorm.h.

30{
31 if (!norm) return "auto";
32 switch (*norm) {
34 return "l2";
36 return "linf";
38 return "max_force_on_atom";
39 }
40 throw std::invalid_argument("invalid convergence force norm");
41}

◆ forEachCutoffPair()

template<typename Function>
void gpr::forEachCutoffPair ( const CutoffPairFeatures & left,
const CutoffPairFeatures & right,
Function && function )

Visit the union of two sparse feature rows in their common pair vocabulary.

Definition at line 105 of file PairCutoff.h.

107{
108 std::size_t i = 0, j = 0;
109 const auto key = [](const CutoffPairFeature& pair) {
110 return std::make_pair(pair.first, pair.second);
111 };
112 while (i < left.size() || j < right.size()) {
113 if (j == right.size() ||
114 (i < left.size() && key(left[i]) < key(right[j]))) {
115 function(&left[i++], nullptr);
116 } else if (i == left.size() || key(right[j]) < key(left[i])) {
117 function(nullptr, &right[j++]);
118 } else {
119 function(&left[i++], &right[j++]);
120 }
121 }
122}

◆ formatRFFFeatureSelection()

std::string gpr::formatRFFFeatureSelection ( const RFFFeatureSelection & report)
nodiscard

Definition at line 273 of file RFFSelection.cpp.

274{
275 if (!report.detail.empty()) return report.detail;
276 std::ostringstream out;
277 out << "RFF feature selection " << report.status << " D=" << report.features
278 << " fit=" << report.fit_geometries
279 << " holdout=" << report.holdout_geometries;
280 return out.str();
281}

◆ gprdUnflaggedDimerOptions()

CanonicalDimerDefaultOptions gpr::gprdUnflaggedDimerOptions ( )
nodiscard

Options of an unflagged gprd invocation. The CLI member defaults and gpr_dimer_config_defaults both read this record.

Definition at line 79 of file ParameterDefaults.cpp.

80{
82 // gprd --report-level. The canonical helper's own default is 1.
83 options.report_level = 2;
84 return options;
85}

◆ hssvdHermiteCartesianAction()

Eigen::MatrixXd gpr::hssvdHermiteCartesianAction ( const Eigen::MatrixXd & jacobian,
const Eigen::MatrixXd & residuals,
const Eigen::MatrixXd & force_weights,
const Eigen::VectorXd & energy_kernel_weights,
const Eigen::VectorXd & force_kernel_weights,
const Eigen::VectorXd & force_residual_dots,
double energy_kernel_weight_sum,
double force_kernel_residual_dot_sum,
const Eigen::MatrixXd & directions )
nodiscard

Cartesian action of the HS-SVD Hermite weights on directions. Equal-and-opposite energy weights cancel; the result is within one ulp of the cancelled weight scale of the exact residual.

Definition at line 1756 of file Decompose.cpp.

1763{
1764 const Eigen::MatrixXd vq = jacobian * directions;
1765 const Eigen::MatrixXd rv = residuals * vq;
1766 Eigen::MatrixXd desc_hv = -2.0 * energy_kernel_weight_sum * vq;
1767 const Eigen::VectorXd energy_coeff = 4.0 * energy_kernel_weights;
1768 const Eigen::MatrixXd weighted_rv =
1769 (rv.array().colwise() * energy_coeff.array()).matrix();
1770 extendedTransposeAdd(desc_hv, residuals, weighted_rv);
1771
1772 const Eigen::MatrixXd gv = force_weights * vq;
1773 const Eigen::VectorXd force_g_scale = -4.0 * force_kernel_weights;
1774 const Eigen::VectorXd force_rv_scale =
1775 8.0 * force_kernel_weights.array() * force_residual_dots.array();
1776 const Eigen::MatrixXd force_g_coeff =
1777 (rv.array().colwise() * force_g_scale.array()).matrix();
1778 const Eigen::MatrixXd force_r_coeff =
1779 (gv.array().colwise() * force_g_scale.array() +
1780 rv.array().colwise() * force_rv_scale.array())
1781 .matrix();
1782 extendedTransposeAdd(desc_hv, force_weights, force_g_coeff);
1783 extendedTransposeAdd(desc_hv, residuals, force_r_coeff);
1784 desc_hv.noalias() += -4.0 * force_kernel_residual_dot_sum * vq;
1785 return jacobian.transpose() * desc_hv;
1786}

◆ inlaClipToLogBox()

Eigen::VectorXd gpr::detail::inlaClipToLogBox ( const Eigen::VectorXd & theta,
const Eigen::VectorXd & lower,
const Eigen::VectorXd & upper )
inline

Definition at line 134 of file Helpers.h.

137{
138 Eigen::VectorXd clipped = theta;
139 for (Eigen::Index i = 0; i < clipped.size(); ++i) {
140 clipped(i) = std::min(upper(i), std::max(lower(i), clipped(i)));
141 }
142 return clipped;
143}

◆ iterationAllowedByLimit()

bool gpr::iterationAllowedByLimit ( Index_t iteration,
Index_t configured_limit )
nodiscardconstexprnoexcept

Definition at line 90 of file Structures.h.

92{
93 return configured_limit <= 0 || iteration < configured_limit;
94}

◆ jointObservationForceVarianceReduction()

std::optional< JointObservationVarianceReduction > gpr::jointObservationForceVarianceReduction ( const Eigen::MatrixXd & posterior_covariance,
Eigen::Index query_count,
Eigen::Index dimensions,
Eigen::Index candidate_query,
const std::vector< Eigen::Index > & target_queries,
double noise_variance )
nodiscard

Integrated force-variance reduction from one joint energy-force query.

The candidate conditions on its complete energy-and-gradient observation block, while the target trace contains only Cartesian-gradient channels. The resulting score therefore has force-variance units and can rank acquisitions for a force-readiness decision without mixing physical units.

Definition at line 174 of file ObservationAcquisition.cpp.

179{
180 if (dimensions <= 0) return std::nullopt;
181 return jointObservationVarianceReductionImpl(
182 posterior_covariance, query_count, dimensions, candidate_query,
183 target_queries, noise_variance, /*first_target_channel=*/1);
184}

◆ jointObservationVarianceReduction() [1/2]

std::optional< JointObservationVarianceReduction > gpr::jointObservationVarianceReduction ( const Eigen::MatrixXd & posterior_covariance,
Eigen::Index query_count,
Eigen::Index dimensions,
Eigen::Index candidate_query,
const std::vector< Eigen::Index > & target_queries,
double noise_variance )
nodiscard

Integrated variance reduction from one joint energy-force query.

The covariance uses derivative-major Observation ordering: all query energies, followed by each Cartesian gradient component for all queries. Conditioning always uses the candidate's complete D+1 channel block.

Definition at line 162 of file ObservationAcquisition.cpp.

167{
168 return jointObservationVarianceReductionImpl(
169 posterior_covariance, query_count, dimensions, candidate_query,
170 target_queries, noise_variance, /*first_target_channel=*/0);
171}

◆ jointObservationVarianceReduction() [2/2]

std::optional< JointObservationVarianceReduction > gpr::jointObservationVarianceReduction ( Eigen::MatrixXd candidate_covariance,
const Eigen::MatrixXd & target_candidate_covariance,
double target_variance,
double noise_variance )
nodiscard

Integrated reduction from the candidate block, target cross block, and target diagonal sum. No covariance between distinct targets is needed.

Definition at line 97 of file ObservationAcquisition.cpp.

101{
102 const Eigen::Index channels_per_query = candidate_covariance.rows();
103 const Eigen::Index target_channel_count =
104 target_candidate_covariance.rows();
105 if (channels_per_query <= 0 || target_channel_count <= 0 ||
106 candidate_covariance.cols() != channels_per_query ||
107 target_candidate_covariance.cols() != channels_per_query ||
108 !candidate_covariance.allFinite() ||
109 !target_candidate_covariance.allFinite() ||
110 !std::isfinite(target_variance) || !std::isfinite(noise_variance) ||
111 noise_variance < 0.0)
112 return std::nullopt;
113 candidate_covariance =
114 0.5 * (candidate_covariance + candidate_covariance.transpose()).eval();
115 candidate_covariance.diagonal().array() += noise_variance;
116
117 Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> solver(candidate_covariance);
118 if (solver.info() != Eigen::Success || !solver.eigenvalues().allFinite() ||
119 !solver.eigenvectors().allFinite()) {
120 return std::nullopt;
121 }
122 const double spectral_scale =
123 std::max(1.0, solver.eigenvalues().cwiseAbs().maxCoeff());
124 const double rank_tolerance =
125 std::numeric_limits<double>::epsilon() *
126 static_cast<double>(std::max<Eigen::Index>(channels_per_query, 1)) *
127 spectral_scale;
128 if (solver.eigenvalues().minCoeff() < -rank_tolerance) {
129 return std::nullopt;
130 }
131 Eigen::VectorXd inverse_eigenvalues =
132 Eigen::VectorXd::Zero(channels_per_query);
133 for (Eigen::Index i = 0; i < channels_per_query; ++i) {
134 if (solver.eigenvalues()(i) > rank_tolerance) {
135 inverse_eigenvalues(i) = 1.0 / solver.eigenvalues()(i);
136 }
137 }
138 const Eigen::MatrixXd candidate_inverse = solver.eigenvectors() *
139 inverse_eigenvalues.asDiagonal() *
140 solver.eigenvectors().transpose();
141
142 const Eigen::MatrixXd weighted_cross =
143 target_candidate_covariance * candidate_inverse;
144 double variance_reduction =
145 (weighted_cross.array() * target_candidate_covariance.array()).sum();
146 const double reduction_tolerance =
147 std::numeric_limits<double>::epsilon() *
148 std::max(
149 {1.0, std::abs(target_variance), std::abs(variance_reduction)}) *
150 static_cast<double>(std::max<Eigen::Index>(target_channel_count, 1));
151 if (variance_reduction < -reduction_tolerance ||
152 !std::isfinite(variance_reduction) || !std::isfinite(target_variance)) {
153 return std::nullopt;
154 }
155 if (variance_reduction < 0.0) variance_reduction = 0.0;
156
157 return JointObservationVarianceReduction{variance_reduction,
158 target_variance};
159}

◆ laplaceMarginalLogLik()

double gpr::laplaceMarginalLogLik ( const EigenMatrix & K,
const Eigen::VectorXd & y,
const Eigen::VectorXd & f_mode,
const ObservationLikelihood & ol )

Laplace approximation to log p(y | theta) given prior K and the converged posterior mode f_mode (R&W eq. 3.32):

log p(y|theta) ~= log p(y|f_mode) + log N(f_mode | 0, K)

  • (1/2) log|I + W K|

with W = diag(negHessDiag(y, f_mode)).

Definition at line 56 of file ObservationLikelihood.cpp.

59{
60 const Eigen::Index n = K.rows();
61 Eigen::VectorXd W_diag = ol.negHessDiag(y, f_mode);
62 for (Eigen::Index i = 0; i < n; ++i) {
63 if (W_diag(i) < 0.0) W_diag(i) = 0.0;
64 }
65 const Eigen::VectorXd W_sqrt = W_diag.cwiseSqrt();
66
67 EigenMatrix B = EigenMatrix::Identity(n, n);
68 B += W_sqrt.asDiagonal() * K * W_sqrt.asDiagonal();
69 Eigen::LLT<EigenMatrix> llt_B(B);
70 if (llt_B.info() != Eigen::Success) {
71 throw std::runtime_error("laplaceMarginalLogLik: B Cholesky failed");
72 }
73 // log|B| = 2 * sum log(diag(L_B)).
74 const EigenMatrix L_B = llt_B.matrixL();
75 double log_det_B = 0.0;
76 for (Eigen::Index i = 0; i < n; ++i)
77 log_det_B += std::log(L_B(i, i));
78 log_det_B *= 2.0;
79
80 // log N(f_mode | 0, K) = -(1/2) f^T K^{-1} f - (1/2) log|K|
81 // - (n/2) log(2 pi).
82 Eigen::LLT<EigenMatrix> llt_K(K);
83 if (llt_K.info() != Eigen::Success) {
84 throw std::runtime_error(
85 "laplaceMarginalLogLik: K Cholesky failed (check K is PSD)");
86 }
87 const EigenMatrix L_K = llt_K.matrixL();
88 double log_det_K = 0.0;
89 for (Eigen::Index i = 0; i < n; ++i)
90 log_det_K += std::log(L_K(i, i));
91 log_det_K *= 2.0;
92
93 const Eigen::VectorXd Kinv_f = llt_K.solve(f_mode);
94 constexpr double kLog2Pi = 1.8378770664093453; // log(2 pi)
95 const double log_p_f_prior = -0.5 * f_mode.dot(Kinv_f) - 0.5 * log_det_K -
96 0.5 * static_cast<double>(n) * kLog2Pi;
97
98 const double log_p_y_f = ol.logProb(y, f_mode);
99 return log_p_y_f + log_p_f_prior - 0.5 * log_det_B;
100}
virtual double logProb(const Eigen::VectorXd &y, const Eigen::VectorXd &f) const =0
log p(y | f) summed over observations.

◆ launchedOnOneNode()

bool gpr::launchedOnOneNode ( )
inlinenoexcept

Whether the launcher placed every rank of this run on one node: the Open MPI launcher's world and node-local sizes agree, a Slurm step spans one node, or no launcher started the process (a singleton). Unknown launches count as several nodes.

Definition at line 24 of file MpiLifetime.h.

25{
26 const char* world = std::getenv("OMPI_COMM_WORLD_SIZE");
27 const char* local = std::getenv("OMPI_COMM_WORLD_LOCAL_SIZE");
28 if (world != nullptr && local != nullptr)
29 return std::strcmp(world, local) == 0;
30 if (const char* nodes = std::getenv("SLURM_STEP_NUM_NODES"))
31 return std::strcmp(nodes, "1") == 0;
32 return world == nullptr && std::getenv("PMIX_RANK") == nullptr &&
33 std::getenv("PMI_RANK") == nullptr;
34}

◆ lengthscaleProjectionFloor()

double gpr::lengthscaleProjectionFloor ( double max_pair_distance,
double absolute_floor )
inlinenodiscard

Lower edge of the feasible kernel length-scale domain for the MAP projection in optimize(). Two floors compose: a numerical collapse guard relative to the data diameter, and an absolute caller-set resolution floor (the dimer sets its finite-difference stencil diameter on its self-owned GP). A length scale below the sampling resolution fits sub-stencil noise as signal: the kernel degenerates into a delta comb whose relaxation endpoints scatter into EMD-distinct probes. The resolution floor guards against sub-resolution collapse only: when the training data spans less than the stencil (the two-row bootstrap), it is capped at the data diameter so the projection never forbids fits at the scale of the data itself. A chain-spacing floor (diameter/(n_images-1)) is deliberately NOT part of this domain: forcing the NEB session GP above chain spacing over-smooths the surrogate and moves the converged saddle (Baker14 anchor: 2.36819 eV at free length scales, 3.7772 eV with the chain bound; single-node A/B at 31b415ab).

Definition at line 306 of file GaussianProcessRegression.h.

308{
309 double floor = std::max(1.0e-6, max_pair_distance * 1.0e-3);
310 if (std::isfinite(absolute_floor) && absolute_floor > 0.0 &&
311 std::isfinite(max_pair_distance) && max_pair_distance > 0.0) {
312 floor = std::max(floor, std::min(absolute_floor, max_pair_distance));
313 }
314 return floor;
315}

◆ libraryPublicLayout()

PublicLayoutBytes gpr::libraryPublicLayout ( )

Definition at line 15 of file PublicLayout.cpp.

16{
18 out.gaussian_process = sizeof(GaussianProcessRegression);
19 out.gaussian_process_inverse_diagonal =
20 offsetof(GaussianProcessRegression, training_inverse_diagonal_);
21 out.backend_context = sizeof(linalg::BackendContext);
22 out.backend_context_kokkos_workspace =
23 offsetof(linalg::BackendContext, kokkos_);
24 out.gpneb_config = sizeof(neb::GPNEBConfig);
25 out.gpneb_config_rgmin_method = offsetof(neb::GPNEBConfig, rgmin_method);
26 out.dimer = sizeof(::dimer::Dimer);
27 out.dimer_rgmin_translation = offsetof(::dimer::Dimer, rgmin_trans_);
28 out.atomic_dimer = sizeof(atmd::AtomicDimer);
29 out.atomic_dimer_rgmin_translation =
30 offsetof(atmd::AtomicDimer, rgmin_trans_);
31 return out;
32}
Atomic dimer.
Dimer method.
Definition Dimer.h:59
Configuration for GP-NEB.
Definition GPNEB.h:246

◆ localTraceProduct()

double gpr::detail::localTraceProduct ( const EigenMatrix & A,
const EigenMatrix & B )
inline

Definition at line 44 of file Helpers.h.

45{
46 if (A.rows() != B.rows() || A.cols() != B.cols()) {
47 return std::numeric_limits<double>::quiet_NaN();
48 }
49 double sum = 0.0;
50 const Eigen::Index size = A.size();
51 const double* a = A.data();
52 const double* b = B.data();
53 for (Eigen::Index i = 0; i < size; ++i)
54 sum += a[i] * b[i];
55 return sum;
56}

◆ looCalibrationIsUnityFromCholeskyDiagonal()

bool gpr::looCalibrationIsUnityFromCholeskyDiagonal ( const Eigen::VectorXd & alpha,
const Eigen::VectorXd & diagonal )

Certify unit LOO calibration using diag(L) without forming diag(K^-1). An inconclusive bound returns false and requires the full LOO statistic.

Definition at line 3999 of file StableBasis.cpp.

4001{
4002 if (alpha.size() < 2 || alpha.size() != diagonal.size()) return false;
4003 // q_i = ||L^-1 e_i||^2 >= 1 / L_ii^2 gives
4004 // alpha_i^2 / q_i <= (alpha_i L_ii)^2. A strict majority below the
4005 // chi-square median bounds both middle entries for an even sample.
4006 // The margin keeps a rounded score at the boundary inconclusive.
4007 constexpr double kChiSquare1Median = 0.4549364231195727;
4008 const double limit = std::sqrt(kChiSquare1Median) *
4009 (1.0 - 128.0 * std::numeric_limits<double>::epsilon());
4010 Eigen::Index below = 0;
4011 for (Eigen::Index i = 0; i < alpha.size(); ++i) {
4012 if (!std::isfinite(alpha(i)) || !std::isfinite(diagonal(i)) ||
4013 !(diagonal(i) > 0.0))
4014 return false;
4015 if (std::abs(alpha(i)) * diagonal(i) < limit) ++below;
4016 }
4017 return below > alpha.size() / 2;
4018}

◆ looVarianceCalibrationFactor()

double gpr::looVarianceCalibrationFactor ( const Eigen::VectorXd & alpha,
const Eigen::VectorXd & inv_diag )

Leave-one-out variance calibration factor from posterior weights alpha and the diagonal of the noisy precision (K + sigma2 I)^-1: the median squared LOO z-score over the chi-square(1) median, floored at 1. Shared by the dense Cholesky and HS-SVD backends.

Definition at line 4020 of file StableBasis.cpp.

4022{
4023 // z_i^2 = alpha_i^2 / q_i with alpha = (K + sigma2 I)^-1 y and
4024 // q_i = [(K + sigma2 I)^-1]_ii is the squared leave-one-out z-score of
4025 // row i (Sundararajan-Keerthi). A calibrated posterior has z_i marginally
4026 // standard normal, so z_i^2 ~ chi-square(1) with population median
4027 // Phi^-1(0.75)^2 = 0.4549364231195727 (a distributional constant). The
4028 // factor is the median z^2 over that reference; calibrated or
4029 // under-confident models (c <= 1) are left untouched. Backend-independent
4030 // on purpose: the dense Cholesky and the HS-SVD dual basis must report
4031 // the same calibrated variance for the same data.
4032 if (alpha.size() < 2 || alpha.size() != inv_diag.size()) return 1.0;
4033 std::vector<double> z2;
4034 z2.reserve(static_cast<std::size_t>(alpha.size()));
4035 for (Eigen::Index i = 0; i < alpha.size(); ++i) {
4036 const double q = inv_diag(i);
4037 if (!(q > 0.0) || !std::isfinite(q) || !std::isfinite(alpha(i)))
4038 return 1.0;
4039 z2.push_back(alpha(i) * alpha(i) / q);
4040 }
4041 std::sort(z2.begin(), z2.end());
4042 const std::size_t n = z2.size();
4043 const double median_z2 =
4044 (n % 2 == 1) ? z2[n / 2] : 0.5 * (z2[n / 2 - 1] + z2[n / 2]);
4045 constexpr double kChiSquare1Median = 0.4549364231195727;
4046 const double c = median_z2 / kChiSquare1Median;
4047 return (std::isfinite(c) && c > 1.0) ? c : 1.0;
4048}

◆ makeAnalyticKernelMeanHessian()

KernelOperator::MeanHessianPreparation gpr::makeAnalyticKernelMeanHessian ( const std::shared_ptr< const KernelOperator > & kernel,
const Eigen::MatrixXd & training,
const Eigen::VectorXd & weights )
nodiscard

Definition at line 139 of file KernelOperator.cpp.

142{
143 requireFittedKernel(kernel, training, weights,
144 "invalid fitted kernel Hessian");
145 if (auto prepare = kernel->prepareMeanHessian(training, weights))
146 return prepare;
147 if (auto fitted = kernel->prepareMeanHessianVector(training, weights))
148 return prepareFromVector(std::move(fitted), training.cols());
149 return {};
150}

◆ makeAnalyticKernelMeanHessianVector()

KernelOperator::MeanHessianFunction gpr::makeAnalyticKernelMeanHessianVector ( const std::shared_ptr< const KernelOperator > & kernel,
const Eigen::MatrixXd & training,
const Eigen::VectorXd & weights )
nodiscard

The kernel's own Hessian preparation, or an empty function when it has none. Unlike makeKernelMeanHessian*, no meanHessianVector stand-in is made, so an empty result means the kernel has no analytic Hessian to prepare.

Definition at line 130 of file KernelOperator.cpp.

133{
134 requireFittedKernel(kernel, training, weights,
135 "invalid fitted kernel derivative");
136 return kernel->prepareMeanHessianVector(training, weights);
137}

◆ makeChartScalarKernel()

std::shared_ptr< const KernelOperator > gpr::makeChartScalarKernel ( std::shared_ptr< const geometry::CoordinateChart > chart,
double magnitude_variance,
double length_scale,
ChartScalarKernel kernel )
nodiscard

Squared-exponential Pullback unless kernel is Matern52.

Definition at line 390 of file Matern52.cpp.

393{
395 return std::make_shared<Pullback>(std::move(chart), magnitude_variance,
396 length_scale);
397 }
398 if (kernel == ChartScalarKernel::Matern52) {
399 return std::make_shared<Matern52>(std::move(chart), magnitude_variance,
400 length_scale);
401 }
402 throw std::invalid_argument("unknown chart scalar kernel");
403}

◆ makeKernelCrossCovariance()

KernelOperator::CrossCovarianceFunction gpr::makeKernelCrossCovariance ( std::shared_ptr< const KernelOperator > kernel,
const Eigen::MatrixXd & training )
nodiscard

Definition at line 73 of file KernelOperator.cpp.

76{
77 if (!kernel || training.cols() <= 0 || !training.allFinite())
78 throw std::invalid_argument("invalid fitted covariance operand");
79 if (auto prepared = kernel->prepareCrossCovariance(training))
80 return prepared;
81 return [kernel = std::move(kernel),
82 training](const Eigen::MatrixXd& query) -> Eigen::MatrixXd {
83 return kernel->jointEnergyGradientCrossCovariance(query, training);
84 };
85}

◆ makeKernelMean()

KernelOperator::MeanFunction gpr::makeKernelMean ( std::shared_ptr< const KernelOperator > kernel,
const Eigen::MatrixXd & training,
const Eigen::VectorXd & weights )
nodiscard

Owning fitted mean, using the kernel's representation or its exact product.

Definition at line 87 of file KernelOperator.cpp.

90{
91 if (!kernel || training.cols() <= 0 || !training.allFinite() ||
92 weights.size() != training.rows() * (training.cols() + 1) ||
93 !weights.allFinite())
94 throw std::invalid_argument("invalid fitted kernel mean");
95 if (auto prepared = kernel->prepareMean(training, weights)) return prepared;
96 return [kernel = std::move(kernel), training,
97 weights](const Eigen::MatrixXd& query) -> Eigen::VectorXd {
98 return kernel->applyJointCrossCovariance(query, training, weights);
99 };
100}

◆ makeKernelMeanHessian()

KernelOperator::MeanHessianPreparation gpr::makeKernelMeanHessian ( std::shared_ptr< const KernelOperator > kernel,
const Eigen::MatrixXd & training,
const Eigen::VectorXd & weights )
nodiscard

Definition at line 349 of file KernelOperator.cpp.

352{
353 if (auto prepare = makeAnalyticKernelMeanHessian(kernel, training, weights))
354 return prepare;
355 auto refusal_prepare =
356 makeRefusalAwareKernelMeanHessian(std::move(kernel), training, weights);
357 return
358 [refusal_prepare = std::move(refusal_prepare)](
359 const Eigen::VectorXd& position) -> KernelOperator::HessianAction {
360 bool exact_refusal = false;
361 auto action = refusal_prepare(position, exact_refusal);
362 if (!action) return {};
363 return
364 [action = std::move(action)](const Eigen::VectorXd& direction,
365 Eigen::VectorXd& result) {
366 bool direction_refusal = false;
367 return action(direction, result, direction_refusal);
368 };
369 };
370}
std::function< bool(const Eigen::VectorXd &, Eigen::VectorXd &)> HessianAction
KernelOperator::MeanHessianPreparation makeAnalyticKernelMeanHessian(const std::shared_ptr< const KernelOperator > &kernel, const Eigen::MatrixXd &training, const Eigen::VectorXd &weights)
RefusalAwareHessianPreparation makeRefusalAwareKernelMeanHessian(std::shared_ptr< const KernelOperator > kernel, const Eigen::MatrixXd &training, const Eigen::VectorXd &weights, bool *all_exact, bool *has_exact_or_refusal)
Prepare a fitted kernel Hessian action that propagates exact-child refusals through composite operato...

◆ makeKernelMeanHessianMatrix()

KernelOperator::MeanHessianMatrixFunction gpr::makeKernelMeanHessianMatrix ( std::shared_ptr< const KernelOperator > kernel,
const Eigen::MatrixXd & training,
const Eigen::VectorXd & weights )
nodiscard

Dense mean Hessian of a kernel from the columns of its refusal-aware action. A failed column is Refused when an exact child refused it and Unavailable when only a generic child missed; the matrix is left empty in both cases.

Definition at line 372 of file KernelOperator.cpp.

375{
376 if (!kernel || training.cols() <= 0 || !training.allFinite() ||
377 weights.size() != training.rows() * (training.cols() + 1) ||
378 !weights.allFinite())
379 throw std::invalid_argument("invalid fitted kernel Hessian");
381 // The refusal-aware action checks each column's length and finiteness,
382 // so a matrix built from successful columns is finite.
383 return [prepare = makeRefusalAwareKernelMeanHessian(std::move(kernel),
384 training, weights)](
385 const Eigen::VectorXd& position,
386 Eigen::MatrixXd& hessian) -> Status {
387 hessian.resize(0, 0);
388 bool exact_refusal = false;
389 const auto action = prepare(position, exact_refusal);
390 if (!action)
391 return exact_refusal ? Status::Refused : Status::Unavailable;
392 const Eigen::Index dof = position.size();
393 Eigen::MatrixXd result(dof, dof);
394 Eigen::VectorXd column;
395 for (Eigen::Index j = 0; j < dof; ++j) {
396 if (!action(Eigen::VectorXd::Unit(dof, j), column, exact_refusal))
397 return exact_refusal ? Status::Refused : Status::Unavailable;
398 result.col(j) = column;
399 }
400 hessian = std::move(result);
401 return Status::Computed;
402 };
403}

◆ makeKernelMeanHessianVector()

KernelOperator::MeanHessianFunction gpr::makeKernelMeanHessianVector ( std::shared_ptr< const KernelOperator > kernel,
const Eigen::MatrixXd & training,
const Eigen::VectorXd & weights )
nodiscard

Definition at line 152 of file KernelOperator.cpp.

155{
156 if (auto prepared =
157 makeAnalyticKernelMeanHessianVector(kernel, training, weights))
158 return prepared;
159 return [kernel = std::move(kernel), training, weights](
160 const Eigen::VectorXd& position,
161 const Eigen::VectorXd& direction, Eigen::VectorXd& action) {
162 return kernel->meanHessianVector(training, weights, position, direction,
163 action);
164 };
165}
KernelOperator::MeanHessianFunction makeAnalyticKernelMeanHessianVector(const std::shared_ptr< const KernelOperator > &kernel, const Eigen::MatrixXd &training, const Eigen::VectorXd &weights)

◆ makeRefusalAwareKernelMeanHessian()

RefusalAwareHessianPreparation gpr::makeRefusalAwareKernelMeanHessian ( std::shared_ptr< const KernelOperator > kernel,
const Eigen::MatrixXd & training,
const Eigen::VectorXd & weights,
bool * all_exact = nullptr,
bool * has_exact_or_refusal = nullptr )
nodiscard

Prepare a fitted kernel Hessian action that propagates exact-child refusals through composite operators.

Definition at line 167 of file KernelOperator.cpp.

171{
172 if (!kernel || training.cols() <= 0 || !training.allFinite() ||
173 weights.size() != training.rows() * (training.cols() + 1) ||
174 !weights.allFinite())
175 throw std::invalid_argument("invalid fitted kernel Hessian");
176 if (const auto* conditioned =
177 dynamic_cast<const ConditionedKernel*>(kernel.get())) {
178 const auto [positions, combined] =
179 conditioned->meanExpansion(training, weights);
180 return makeRefusalAwareKernelMeanHessian(conditioned->childKernel(),
181 positions, combined, all_exact,
182 has_exact_or_refusal);
183 }
184 const auto& current = *kernel;
185 if (const auto* sum = dynamic_cast<const Sum*>(kernel.get());
186 sum != nullptr && typeid(current) == typeid(Sum)) {
187 struct SummandTerm {
188 RefusalAwareHessianPreparation prepare;
189 bool all_exact = false;
190 bool has_exact_or_refusal = false;
191 };
192 std::vector<SummandTerm> terms;
193 terms.reserve(sum->summands().size());
194 bool every_exact = !sum->summands().empty();
195 bool any_exact_or_refusal = false;
196 for (const auto& child: sum->summands()) {
197 if (!child)
198 throw std::invalid_argument("invalid fitted kernel Hessian");
199 SummandTerm term;
201 child, training, weights, &term.all_exact,
202 &term.has_exact_or_refusal);
203 every_exact = every_exact && term.all_exact;
204 any_exact_or_refusal =
205 any_exact_or_refusal || term.has_exact_or_refusal;
206 terms.push_back(std::move(term));
207 }
208 if (all_exact != nullptr) *all_exact = every_exact;
209 if (has_exact_or_refusal != nullptr)
210 *has_exact_or_refusal = any_exact_or_refusal;
211 const Eigen::Index dof = training.cols();
212 return [terms = std::move(terms), dof, any_exact_or_refusal](
213 const Eigen::VectorXd& position,
214 bool& exact_refusal) -> RefusalAwareHessianAction {
215 if (position.size() != dof || !position.allFinite()) {
216 if (any_exact_or_refusal) exact_refusal = true;
217 return {};
218 }
219 struct PreparedAction {
221 bool has_exact_or_refusal = false;
222 };
223 std::vector<PreparedAction> actions;
224 actions.reserve(terms.size());
225 bool query_failed = false;
226 for (const auto& term: terms) {
227 bool child_refused = false;
228 auto action = term.prepare(position, child_refused);
229 if (child_refused) exact_refusal = true;
230 if (!action) {
231 query_failed = true;
232 if (term.has_exact_or_refusal) exact_refusal = true;
233 } else {
234 actions.push_back(
235 {std::move(action), term.has_exact_or_refusal});
236 }
237 }
238 if (query_failed) return {};
239 return [actions = std::move(actions), dof, any_exact_or_refusal](
240 const Eigen::VectorXd& direction,
241 Eigen::VectorXd& action, bool& exact_refusal) {
242 if (direction.size() != dof || !direction.allFinite()) {
243 if (any_exact_or_refusal) exact_refusal = true;
244 return false;
245 }
246 ExtendedVector result = ExtendedVector::Zero(dof);
247 bool failed = false;
248 for (const auto& prepared: actions) {
249 Eigen::VectorXd term;
250 bool child_refused = false;
251 if (!prepared.apply(direction, term, child_refused) ||
252 term.size() != dof || !term.allFinite()) {
253 failed = true;
254 if (child_refused || prepared.has_exact_or_refusal)
255 exact_refusal = true;
256 } else if (!failed) {
257 result += term.cast<long double>();
258 }
259 }
260 if (failed) return false;
261 action = result.cast<double>();
262 if (!action.allFinite()) {
263 if (any_exact_or_refusal) exact_refusal = true;
264 return false;
265 }
266 return true;
267 };
268 };
269 }
270 // Refused is the kernel's answer. A subclass that still prepares a
271 // Hessian does not turn that answer into a product.
272 if (kernel->meanCurvature() == KernelOperator::MeanCurvature::Refused) {
273 if (all_exact != nullptr) *all_exact = false;
274 if (has_exact_or_refusal != nullptr) *has_exact_or_refusal = true;
275 const Eigen::Index dof = training.cols();
276 return [dof](const Eigen::VectorXd& position,
277 bool& exact_refusal) -> RefusalAwareHessianAction {
278 (void)position;
279 (void)dof;
280 exact_refusal = true;
281 return {};
282 };
283 }
284 if (auto prepare = kernel->prepareMeanHessian(training, weights)) {
285 if (all_exact != nullptr) *all_exact = true;
286 if (has_exact_or_refusal != nullptr) *has_exact_or_refusal = true;
287 const Eigen::Index dof = training.cols();
288 return [prepare = std::move(prepare), dof](
289 const Eigen::VectorXd& position,
290 bool& exact_refusal) -> RefusalAwareHessianAction {
291 if (position.size() != dof || !position.allFinite()) {
292 exact_refusal = true;
293 return {};
294 }
295 auto action = prepare(position);
296 if (!action) {
297 exact_refusal = true;
298 return {};
299 }
300 return [action = std::move(action), dof](
301 const Eigen::VectorXd& direction,
302 Eigen::VectorXd& result, bool& exact_refusal) {
303 if (direction.size() != dof || !direction.allFinite() ||
304 !action(direction, result) || result.size() != dof ||
305 !result.allFinite()) {
306 exact_refusal = true;
307 return false;
308 }
309 return true;
310 };
311 };
312 }
313 const bool leaf_refuses =
314 kernel->meanCurvature() != KernelOperator::MeanCurvature::Unknown;
315 if (all_exact != nullptr) *all_exact = false;
316 if (has_exact_or_refusal != nullptr) *has_exact_or_refusal = leaf_refuses;
317 const auto fitted = makeKernelMeanHessianVector(kernel, training, weights);
318 const Eigen::Index dof = training.cols();
319 return [fitted, dof, leaf_refuses](
320 const Eigen::VectorXd& position,
321 bool& exact_refusal) -> RefusalAwareHessianAction {
322 if (position.size() != dof || !position.allFinite()) {
323 if (leaf_refuses) exact_refusal = true;
324 return {};
325 }
326 return [fitted, position, dof, leaf_refuses](
327 const Eigen::VectorXd& direction, Eigen::VectorXd& result,
328 bool& exact_refusal) {
329 if (direction.size() != dof || !direction.allFinite()) {
330 if (leaf_refuses) exact_refusal = true;
331 return false;
332 }
333 bool applied = false;
334 try {
335 applied = fitted(position, direction, result);
337 exact_refusal = true;
338 return false;
339 }
340 if (!applied || result.size() != dof || !result.allFinite()) {
341 if (leaf_refuses) exact_refusal = true;
342 return false;
343 }
344 return true;
345 };
346 };
347}
KernelOperator::MeanHessianFunction makeKernelMeanHessianVector(std::shared_ptr< const KernelOperator > kernel, const Eigen::MatrixXd &training, const Eigen::VectorXd &weights)

◆ medianPairwiseDistance()

double gpr::medianPairwiseDistance ( const EigenMatrix & R_train)

Median of the strict-upper-triangle pairwise Euclidean row distances over a training set. Degree-1 homogeneous: median(s*X) = s*median(X).

Returns
Median pairwise distance, or 0.0 when fewer than two rows.

Definition at line 13 of file ScaleFreeTrustRegion.cpp.

14{
15 const int n = static_cast<int>(R_train.rows());
16 if (n < 2) return 0.0; // no inter-sample spread
17
18 std::vector<double> pair_dists;
19 pair_dists.reserve(static_cast<std::size_t>(n) * (n - 1) / 2);
20 for (int i = 0; i < n; ++i) {
21 for (int j = i + 1; j < n; ++j) {
22 const double d = (R_train.row(i) - R_train.row(j)).norm();
23 if (std::isfinite(d)) pair_dists.push_back(d);
24 }
25 }
26 if (pair_dists.empty()) return 0.0;
27
28 const std::size_t m = pair_dists.size();
29 const std::size_t mid = m / 2;
30 std::nth_element(pair_dists.begin(), pair_dists.begin() + mid,
31 pair_dists.end());
32 double median = pair_dists[mid];
33 if (m % 2 == 0) {
34 const double lo =
35 *std::max_element(pair_dists.begin(), pair_dists.begin() + mid);
36 median = 0.5 * (lo + median);
37 }
38 return median;
39}

◆ ownsBlock()

bool gpr::ownsBlock ( long block_idx,
int rank,
int nprocs,
bool serial_per_rank )
inlinenodiscard

Definition at line 22 of file BlockOwnership.h.

24{
25 if (serial_per_rank) return true;
26 return (block_idx % nprocs) == rank;
27}

◆ ownsBlockIfReduce()

bool gpr::ownsBlockIfReduce ( long block_idx,
int rank,
int nprocs,
bool do_reduce )
inlinenodiscard

Definition at line 31 of file BlockOwnership.h.

33{
34 return ownsBlock(block_idx, rank, nprocs, /*serial_per_rank=*/!do_reduce);
35}
bool ownsBlock(long block_idx, int rank, int nprocs, bool serial_per_rank)

◆ parseForceNorm()

std::optional< ConvergenceNormType > gpr::parseForceNorm ( std::string_view name)
inline

An omitted norm preserves the search's dimension-dependent default.

Definition at line 16 of file ForceNorm.h.

17{
18 if (name.empty() || name == "auto") return std::nullopt;
19 if (name == "l2" || name == "l2_norm" || name == "l2Norm")
21 if (name == "linf" || name == "linf_norm" || name == "linfNorm")
23 if (name == "max_force_on_atom" || name == "maxForceOnAtom")
25 throw std::invalid_argument("unknown convergence force norm: " +
26 std::string(name));
27}

◆ permuteMatrixRows()

EigenMatrix gpr::permuteMatrixRows ( const EigenMatrix & input,
const StructuredPermutation & p )
inline

Definition at line 236 of file PermutationUtils.h.

238{
239 EigenMatrix output(input.rows(), input.cols());
240 for (Index_t i = 0; i < static_cast<Index_t>(p.perm.size()); ++i)
241 output.row(i) = input.row(p.perm[i]);
242 return output;
243}

◆ permuteSymmetricMatrix()

EigenMatrix gpr::permuteSymmetricMatrix ( const EigenMatrix & input,
const StructuredPermutation & p )
inline

Definition at line 254 of file PermutationUtils.h.

256{
257 EigenMatrix output(input.rows(), input.cols());
258 for (Index_t i = 0; i < static_cast<Index_t>(p.perm.size()); ++i) {
259 for (Index_t j = 0; j < static_cast<Index_t>(p.perm.size()); ++j) {
260 output(i, j) = input(p.perm[i], p.perm[j]);
261 }
262 }
263 return output;
264}

◆ permuteVector()

Eigen::VectorXd gpr::permuteVector ( const Eigen::VectorXd & input,
const StructuredPermutation & p )
inline

Definition at line 218 of file PermutationUtils.h.

220{
221 Eigen::VectorXd output(input.size());
222 for (Index_t i = 0; i < static_cast<Index_t>(p.perm.size()); ++i)
223 output(i) = input(p.perm[i]);
224 return output;
225}

◆ planRFFFeatureValidation()

RFFValidationPlan gpr::planRFFFeatureValidation ( int n_geometries,
int cartesian_dimension,
std::uint64_t memory_cap_bytes = kRFFValidationMemoryCapBytes )
nodiscard

Counts for n_geometries rows of cartesian_dimension coordinates. The fit is the longest farthest-point prefix whose joint Gram fits in memory_cap_bytes, leaving at least one hold-out when there are two or more geometries. Feature counts are the powers of two from 1 through the largest power of two that is twice-overdetermined on both the fit and the full design and whose normal matrix fits in the same cap.

Definition at line 171 of file RFFSelection.cpp.

174{
176 plan.full_geometries = n_geometries;
177 plan.cartesian_dimension = cartesian_dimension;
178 plan.memory_cap_bytes = clampCapBytes(memory_cap_bytes);
179 if (n_geometries < 0 || cartesian_dimension <= 0) return plan;
180
181 const std::int64_t rows_per_geometry =
182 static_cast<std::int64_t>(cartesian_dimension) + 1;
183 const std::int64_t full_rows =
184 static_cast<std::int64_t>(n_geometries) * rows_per_geometry;
185 plan.full_gram_bytes = gramBytes(full_rows);
186 if (n_geometries < 2) {
187 plan.deferred = true;
188 return plan;
189 }
190
191 const int order_cap = maxDenseOrder(memory_cap_bytes);
192 const std::int64_t raw_geometry_cap =
193 rows_per_geometry > 0
194 ? static_cast<std::int64_t>(order_cap) / rows_per_geometry
195 : 0;
196 const int geometry_cap = static_cast<int>(std::min<std::int64_t>(
197 std::numeric_limits<int>::max(), raw_geometry_cap));
198 if (geometry_cap < 1) return plan;
199
200 const bool full_fits = full_rows <= order_cap;
201 int fit = 0;
202 int holdout = 0;
203 if (full_fits) {
204 holdout = std::max(1, n_geometries / 4);
205 fit = n_geometries - holdout;
206 if (fit > geometry_cap) {
207 fit = geometry_cap;
208 holdout = n_geometries - fit;
209 }
210 } else {
211 fit = std::min(n_geometries - 1, geometry_cap);
212 holdout = n_geometries - fit;
213 }
214 if (fit < 1 || holdout < 1) return plan;
215
216 const std::int64_t joint_rows =
217 static_cast<std::int64_t>(fit) * rows_per_geometry;
218 if (joint_rows > std::numeric_limits<int>::max()) return plan;
219 const std::int64_t guard = std::min(joint_rows / 2, full_rows / 2);
220 const int capped_guard = static_cast<int>(std::min<std::int64_t>(
221 guard, normalMatrixFeatureLimit(memory_cap_bytes)));
222 const int feature_limit = largestPowerOfTwoAtMost(capped_guard);
223 if (feature_limit < 1) return plan;
224
225 plan.fit_geometries = fit;
226 plan.holdout_geometries = holdout;
227 plan.joint_rows = static_cast<int>(joint_rows);
228 plan.feature_start = 1;
229 plan.feature_limit = feature_limit;
230 plan.exact_gram_bytes = gramBytes(joint_rows);
231 plan.admissible = true;
232 return plan;
233}

◆ principledKappaMaxDefault()

double gpr::detail::principledKappaMaxDefault ( )
inline

Definition at line 244 of file Helpers.h.

245{
246 return 1.0 / std::sqrt(std::numeric_limits<double>::epsilon());
247}

◆ priorFreeReplicatedInverse()

bool gpr::priorFreeReplicatedInverse ( bool cholmod,
bool scalapack,
bool slate,
bool unregularized,
bool use_hssvd_gradient )
inline

Whether the prior-free marginal-likelihood gradient may form a replicated K^{-1}.

Eigen's prior-free fit was measured on that inverse: the solve-based trace disagrees by about cond(K) * eps and the fit then stops one step early. CHOLMOD's solve already takes the measured number of steps. ScaLAPACK and SLATE (which also defines GPR_LINALG_SCALAPACK) take the trace from the distributed factor and never read a replicated inverse, so gathering one only costs N^2 memory per rank.

Definition at line 19 of file PriorFreeInverse.h.

22{
23 if (cholmod || scalapack || slate) return false;
24 return unregularized && !use_hssvd_gradient;
25}

◆ priorParametersVector() [1/2]

Eigen::Vector3d gpr::detail::priorParametersVector ( const PriorBase & prior)
inline

Definition at line 157 of file Helpers.h.

158{
159 Eigen::Vector3d out;
160 out << prior.getMu(), prior.getS2(), prior.getNu();
161 return out;
162}
double getMu() const
Definition PriorBase.h:48
double getS2() const
Definition PriorBase.h:53
double getNu() const
Definition PriorBase.h:58

◆ priorParametersVector() [2/2]

Eigen::Vector3d gpr::detail::priorParametersVector ( const PriorBase & prior)
inline

Definition at line 157 of file Helpers.h.

158{
159 Eigen::Vector3d out;
160 out << prior.getMu(), prior.getS2(), prior.getNu();
161 return out;
162}

◆ radialPairFeatures() [1/2]

std::vector< CutoffPairFeatures > gpr::radialPairFeatures ( const Coord & positions,
const AtomsConfiguration & configuration )
nodiscard

Radial features with analytic Cartesian curvature. A positive cutoff selects neighbours; zero retains every active moving-atom pair.

Definition at line 28 of file PairCutoff.cpp.

30{
31 return radialPairFeatures(positions, configuration, 0.0);
32}

◆ radialPairFeatures() [2/2]

std::vector< CutoffPairFeatures > gpr::radialPairFeatures ( const Coord & positions,
const AtomsConfiguration & configuration,
double far_radius )
nodiscard

A positive far radius compresses distant frozen atoms into linear features in the fixed reference chart. It cannot be combined with a cutoff.

Definition at line 34 of file PairCutoff.cpp.

37{
38 if (!std::isfinite(far_radius) || far_radius < 0.0)
39 throw std::invalid_argument(
40 "far-field radius must be finite and nonnegative");
41 if (far_radius > 0.0 && configuration.pair_cutoff > 0.0)
42 throw std::invalid_argument(
43 "far-field compression and pair cutoff are exclusive");
44 const PairCutoff cutoff(configuration.pair_cutoff,
45 configuration.pair_cutoff_width);
46 const Eigen::Index moving = configuration.atoms_mov.type.size();
47 const Eigen::Index frozen = configuration.atoms_froz_active.type.size();
48 if (positions.cols() != 3 * moving || !positions.allFinite() ||
49 configuration.atoms_froz_active.positions.size() != 3 * frozen)
50 throw std::invalid_argument(
51 "pair descriptor coordinates have incompatible dimensions");
52 std::array<double, 9> cell{};
53 std::copy_n(configuration.cell, 9, cell.begin());
54 const geometry::PairBox box(cell);
55 const std::array<bool, 3> periodic = box.periodicAxes();
56 std::vector<double> points(3 * (moving + frozen));
57 std::copy_n(configuration.atoms_froz_active.positions.data(), 3 * frozen,
58 points.data() + 3 * moving);
59 // The vocabulary and the far-field tensor depend only on the model.
60 // Reuse them for every row, including rows that cross the near/far radius.
61 std::vector<std::pair<Eigen::Index, Eigen::Index>> fixed_pairs;
62 CutoffPairFeatures linear_features;
63 if (configuration.pair_cutoff == 0.0) {
64 for (Eigen::Index first = 0; first < moving; ++first) {
65 const double* centre =
66 far_radius > 0.0 ? aux::farFieldCentre(configuration, first)
67 : nullptr;
68 std::vector<Eigen::Matrix3d> tensors(
69 far_radius > 0.0 ? configuration.n_pt : 0,
70 Eigen::Matrix3d::Zero());
71 for (Eigen::Index second = first + 1; second < moving + frozen;
72 ++second) {
73 if (centre && second >= moving) {
74 Eigen::Vector3d displacement;
75 box.displacement(points.data() + 3 * second, centre,
76 displacement.data());
77 const double r2 = displacement.squaredNorm();
78 if (r2 >= far_radius * far_radius) {
79 const auto type = configuration.pairtype(
80 configuration.atoms_mov.type(first),
81 configuration.atoms_froz_active.type(second -
82 moving));
83 if (type >= 0 && type < configuration.n_pt)
84 tensors[type] += displacement *
85 displacement.transpose() /
86 (r2 * r2 * r2);
87 continue;
88 }
89 }
90 fixed_pairs.emplace_back(first, second);
91 }
92 for (Eigen::Index type = 0;
93 type < static_cast<Eigen::Index>(tensors.size()); ++type) {
94 if (tensors[type].isZero(0.0)) continue;
95 const Eigen::SelfAdjointEigenSolver<Eigen::Matrix3d> factor(
96 tensors[type]);
97 if (factor.info() != Eigen::Success)
98 throw std::runtime_error(
99 "far-field tensor factorization failed");
100 const double tolerance =
101 64 * std::numeric_limits<double>::epsilon() *
102 tensors[type].norm();
103 if (factor.eigenvalues().minCoeff() < -tolerance)
104 throw std::runtime_error(
105 "far-field tensor is not positive semidefinite");
106 for (Eigen::Index dim = 0; dim < 3; ++dim) {
107 // Rounding can put a null eigenvalue just below zero.
108 const double scale =
109 std::sqrt(std::max(0.0, factor.eigenvalues()(dim)));
110 linear_features.push_back(
111 {first, moving + frozen + 3 * type + dim, type, 0.0,
112 scale * factor.eigenvectors().col(dim),
113 Eigen::Matrix3d::Zero()});
114 }
115 }
116 }
117 }
118 std::vector<CutoffPairFeatures> result(positions.rows());
119 for (Eigen::Index row = 0; row < positions.rows(); ++row) {
120 std::copy_n(positions.data() + row * positions.cols(), positions.cols(),
121 points.data());
122 std::vector<std::pair<Eigen::Index, Eigen::Index>> pairs;
123 if (configuration.pair_cutoff > 0.0) {
124 for (const auto& neighbor: geometry::cutoffNeighbors(
125 points.data(), moving + frozen, cell, periodic,
126 configuration.pair_cutoff)) {
127 const auto first = static_cast<Eigen::Index>(
128 std::min(neighbor.first, neighbor.second));
129 const auto second = static_cast<Eigen::Index>(
130 std::max(neighbor.first, neighbor.second));
131 if (first == second || first >= moving) continue;
132 pairs.emplace_back(first, second);
133 }
134 std::sort(pairs.begin(), pairs.end());
135 pairs.erase(std::unique(pairs.begin(), pairs.end()), pairs.end());
136 } else {
137 pairs = fixed_pairs;
138 }
139 auto& features = result[row];
140 features.reserve(pairs.size() + linear_features.size());
141 for (const auto& [first, second]: pairs) {
142 const auto first_type = configuration.atoms_mov.type(first);
143 const auto second_type =
144 second < moving
145 ? configuration.atoms_mov.type(second)
146 : configuration.atoms_froz_active.type(second - moving);
147 const Eigen::Index type =
148 configuration.pairtype(first_type, second_type);
149 if (type < 0 || type >= configuration.n_pt) continue;
150 Eigen::Vector3d displacement;
151 box.displacement(points.data() + 3 * second,
152 points.data() + 3 * first, displacement.data());
153 const double radius = displacement.norm();
154 if (configuration.pair_cutoff > 0.0 &&
155 radius >= configuration.pair_cutoff)
156 continue;
157 const auto radial = cutoff(radius);
158 const Eigen::Vector3d direction = displacement / radius;
159 const Eigen::Vector3d gradient = radial.first * direction;
160 const Eigen::Matrix3d hessian =
161 (radial.second - radial.first / radius) * direction *
162 direction.transpose() +
163 (radial.first / radius) * Eigen::Matrix3d::Identity();
164 features.push_back(
165 {first, second, type, radial.value, gradient, hessian});
166 }
167 for (auto feature: linear_features) {
168 Eigen::Vector3d offset;
169 box.displacement(aux::farFieldCentre(configuration, feature.first),
170 points.data() + 3 * feature.first, offset.data());
171 feature.value = feature.gradient.dot(offset);
172 features.push_back(std::move(feature));
173 }
174 if (!linear_features.empty())
175 std::sort(features.begin(), features.end(),
176 [](const auto& a, const auto& b) {
177 return std::make_pair(a.first, a.second) <
178 std::make_pair(b.first, b.second);
179 });
180 }
181 return result;
182}
const double * farFieldCentre(const gpr::AtomsConfiguration &conf, Eigen::Index atom)
Definition FarField.h:15
std::vector< CutoffPair > cutoffNeighbors(const double *positions, std::size_t count, const std::array< double, 9 > &cell, const std::array< bool, 3 > &periodic, double cutoff)
std::vector< CutoffPairFeature > CutoffPairFeatures
Definition PairCutoff.h:90
AtomsPositionAndType atoms_froz_active
Info on active frozen atoms.
Definition Structures.h:841

◆ radialPairSquaredDistances()

std::vector< FieldMatrixd > gpr::radialPairSquaredDistances ( const Coord & left,
const Coord & right,
const AtomsConfiguration & configuration,
const FieldMatrixd & lengths,
double far_radius )

Definition at line 194 of file PairCutoff.cpp.

198{
199 const Eigen::Index coordinates = 3 * configuration.atoms_mov.type.size();
200 if (left.cols() < coordinates || right.cols() < coordinates)
201 throw std::invalid_argument(
202 "pair distance rows do not contain every moving coordinate");
203 // Covariance assembly appends observation/channel indices to each row.
204 const auto left_features = radialPairFeatures(left.leftCols(coordinates),
205 configuration, far_radius);
206 const auto right_features = radialPairFeatures(right.leftCols(coordinates),
207 configuration, far_radius);
208 const Eigen::Index types =
209 lengths.size() == 1 ? configuration.n_pt : lengths.size();
210 std::vector<FieldMatrixd> result(
211 types, FieldMatrixd::Zero(left.rows(), right.rows()));
212 for (Eigen::Index i = 0; i < left.rows(); ++i) {
213 for (Eigen::Index j = 0; j < right.rows(); ++j) {
215 left_features[i], right_features[j],
216 [&](const CutoffPairFeature* a, const CutoffPairFeature* b) {
217 const Eigen::Index type = a ? a->type : b->type;
218 if (type >= types) return;
219 const double length =
220 lengths.data()[lengths.size() == 1 ? 0 : type];
221 const double delta =
222 (a ? a->value : 0.0) - (b ? b->value : 0.0);
223 result[type](i, j) +=
224 2.0 * delta * delta / (length * length);
225 });
226 }
227 }
228 return result;
229}
void forEachCutoffPair(const CutoffPairFeatures &left, const CutoffPairFeatures &right, Function &&function)
Visit the union of two sparse feature rows in their common pair vocabulary.
Definition PairCutoff.h:105

◆ reduce_laplace_factor_vectors_in_grid_order() [1/3]

template<typename EigenObject>
bool gpr::detail::reduce_laplace_factor_vectors_in_grid_order ( std::vector< EigenObject > & factor_values,
linalg::BackendContext & context )
inline

Definition at line 196 of file Helpers.h.

198{
199 if (factor_values.empty()) return true;
200
201 const Eigen::Index n_values = factor_values.front().size();
202 for (const auto& values: factor_values) {
203 if (values.size() != n_values) return false;
204 }
205 const Eigen::Index n_factors =
206 static_cast<Eigen::Index>(factor_values.size());
207 const Eigen::Index n_total = n_values * n_factors;
208 if (n_total > std::numeric_limits<int>::max()) return false;
209
210#ifdef GPR_LINALG_SCALAPACK
211 if (context.mpi().nprocs > 1 && n_total > 0) {
212 std::vector<double> buffer(static_cast<std::size_t>(n_total), 0.0);
213 for (Eigen::Index k = 0; k < n_factors; ++k) {
214 std::copy_n(factor_values[static_cast<std::size_t>(k)].data(),
215 static_cast<std::size_t>(n_values),
216 buffer.data() + static_cast<std::size_t>(k * n_values));
217 }
218
219 context.ordered_sum_bcast(buffer.data(), static_cast<int>(n_total));
220
221 for (Eigen::Index k = 0; k < n_factors; ++k) {
222 std::copy_n(buffer.data() + static_cast<std::size_t>(k * n_values),
223 static_cast<std::size_t>(n_values),
224 factor_values[static_cast<std::size_t>(k)].data());
225 }
226 }
227#endif
228
229 return true;
230}

◆ reduce_laplace_factor_vectors_in_grid_order() [2/3]

template<typename EigenObject>
bool gpr::detail::reduce_laplace_factor_vectors_in_grid_order ( std::vector< EigenObject > & factor_values,
linalg::BackendContext & context )
inline

Definition at line 196 of file Helpers.h.

198{
199 if (factor_values.empty()) return true;
200
201 const Eigen::Index n_values = factor_values.front().size();
202 for (const auto& values: factor_values) {
203 if (values.size() != n_values) return false;
204 }
205 const Eigen::Index n_factors =
206 static_cast<Eigen::Index>(factor_values.size());
207 const Eigen::Index n_total = n_values * n_factors;
208 if (n_total > std::numeric_limits<int>::max()) return false;
209
210#ifdef GPR_LINALG_SCALAPACK
211 if (context.mpi().nprocs > 1 && n_total > 0) {
212 std::vector<double> buffer(static_cast<std::size_t>(n_total), 0.0);
213 for (Eigen::Index k = 0; k < n_factors; ++k) {
214 std::copy_n(factor_values[static_cast<std::size_t>(k)].data(),
215 static_cast<std::size_t>(n_values),
216 buffer.data() + static_cast<std::size_t>(k * n_values));
217 }
218
219 context.ordered_sum_bcast(buffer.data(), static_cast<int>(n_total));
220
221 for (Eigen::Index k = 0; k < n_factors; ++k) {
222 std::copy_n(buffer.data() + static_cast<std::size_t>(k * n_values),
223 static_cast<std::size_t>(n_values),
224 factor_values[static_cast<std::size_t>(k)].data());
225 }
226 }
227#endif
228
229 return true;
230}

◆ reduce_laplace_factor_vectors_in_grid_order() [3/3]

template<typename EigenObject>
bool gpr::detail::reduce_laplace_factor_vectors_in_grid_order ( std::vector< EigenObject > & factor_values,
linalg::BackendContext & context )
inline

Definition at line 196 of file Helpers.h.

198{
199 if (factor_values.empty()) return true;
200
201 const Eigen::Index n_values = factor_values.front().size();
202 for (const auto& values: factor_values) {
203 if (values.size() != n_values) return false;
204 }
205 const Eigen::Index n_factors =
206 static_cast<Eigen::Index>(factor_values.size());
207 const Eigen::Index n_total = n_values * n_factors;
208 if (n_total > std::numeric_limits<int>::max()) return false;
209
210#ifdef GPR_LINALG_SCALAPACK
211 if (context.mpi().nprocs > 1 && n_total > 0) {
212 std::vector<double> buffer(static_cast<std::size_t>(n_total), 0.0);
213 for (Eigen::Index k = 0; k < n_factors; ++k) {
214 std::copy_n(factor_values[static_cast<std::size_t>(k)].data(),
215 static_cast<std::size_t>(n_values),
216 buffer.data() + static_cast<std::size_t>(k * n_values));
217 }
218
219 context.ordered_sum_bcast(buffer.data(), static_cast<int>(n_total));
220
221 for (Eigen::Index k = 0; k < n_factors; ++k) {
222 std::copy_n(buffer.data() + static_cast<std::size_t>(k * n_values),
223 static_cast<std::size_t>(n_values),
224 factor_values[static_cast<std::size_t>(k)].data());
225 }
226 }
227#endif
228
229 return true;
230}

◆ reportFatal()

int gpr::reportFatal ( const char * program,
const char * what )
inlinenoexcept

Ends a driver after an exception escaped it: prints the message and returns the exit status 1. On more than one rank the job is aborted through MPI_Abort, since the other ranks may wait in a collective the failing rank never reaches; on one rank an MPI world the driver initialized is finalized. This replaces std::terminate, whose abort leaves a core dump and no message on most launchers.

Definition at line 143 of file MpiLifetime.h.

144{
145 std::fprintf(stderr, "%s: error: %s\n", program, what);
146 std::fflush(stderr);
147#if defined(GPR_HAVE_MPI) || defined(GPR_LINALG_SCALAPACK)
148 int initialized = 0, finalized = 0;
149 MPI_Initialized(&initialized);
150 MPI_Finalized(&finalized);
151 if (initialized && !finalized) {
152 int size = 1;
153 MPI_Comm_size(MPI_COMM_WORLD, &size);
154 if (size > 1) MPI_Abort(MPI_COMM_WORLD, 1);
155 if (MpiLifetime::ownedWorldPending()) MPI_Finalize();
156 }
157#endif
158 return 1;
159}
static bool & ownedWorldPending() noexcept
Set when an owned world was left open by an escaping exception.
Definition MpiLifetime.h:98

◆ requireFinitePriorParameter()

void gpr::requireFinitePriorParameter ( const char * density,
const char * name,
double value )
inline

Definition at line 26 of file PriorScale.h.

28{
29 if (std::isfinite(value)) return;
30 throw std::invalid_argument(std::string(density) + " " + name +
31 " must be finite (got " +
32 std::to_string(value) + ")");
33}

◆ requirePositiveFinitePriorParameter()

void gpr::requirePositiveFinitePriorParameter ( const char * density,
const char * name,
double value )
inline

Definition at line 17 of file PriorScale.h.

19{
20 if (std::isfinite(value) && value > 0.0) return;
21 throw std::invalid_argument(std::string(density) + " " + name +
22 " must be positive and finite (got " +
23 std::to_string(value) + ")");
24}

◆ requireWallClock()

void gpr::requireWallClock ( const std::shared_ptr< const WallClockLimit > & limit)
inline

Definition at line 73 of file PhaseTimers.h.

74{
75 if (limit && limit->reached()) throw WallClockLimitReached{};
76}

◆ resolveTrainingBlockGeometry()

const SexpatCF::CrossBlockGeometry * gpr::resolveTrainingBlockGeometry ( const SexpatCF & covariance,
const TrainingKernelGeometry & geom,
const TrainingKernelGeometryBlock & block,
SexpatCF::CrossBlockGeometry & scratch )
nodiscard

The derivative tensors of one geometry block: the cached copy, or, for a streamed geometry, a rebuild into scratch from the stored coordinate blocks. Returns nullptr when the block cannot be built.

Definition at line 222 of file CovarianceAssembly.cpp.

226{
227 if (!trainingBlockGeometryUsable(geom, block)) return nullptr;
228 if (!geom.streamed || block.derivative_options == 0) {
229 return &block.geometry;
230 }
231 const auto dim_block = [&](Index_t dim) -> const FieldMatrixd* {
232 if (dim < 0 || dim >= static_cast<Index_t>(geom.x_loc_by_dim.size()) ||
233 geom.x_loc_by_dim[static_cast<std::size_t>(dim)].size() == 0) {
234 return nullptr;
235 }
236 return &geom.x_loc_by_dim[static_cast<std::size_t>(dim)];
237 };
238 const FactoredTrainingGeometry* factors = &geom.factors;
239 if (!factors->valid && geom.lazy_factors) {
240 auto& cached = *geom.lazy_factors;
241 std::call_once(cached.initialize, [&] {
242 (void)buildFactoredTrainingGeometry(
243 cached.configuration, cached.coordinates, cached.factors,
244 cached.far_field_radius);
245 });
246 factors = &cached.factors;
247 }
248 if (factors->valid) {
250 *factors, block.block_n, block.block_m,
251 block.derivative_options, scratch)
252 ? &scratch
253 : nullptr;
254 }
255 const FieldMatrixd* x1 = dim_block(block.block_n);
256 const FieldMatrixd* x2 = dim_block(block.block_m);
257 if (x1 == nullptr || x2 == nullptr) return nullptr;
258 FieldMatrixIdx dims1(1, 1), dims2(1, 1);
259 dims1(0, 0) = block.block_n;
260 dims2(0, 0) = block.block_m;
261 if (!geom.shared_coordinates)
262 return covariance.buildCrossBlockGeometry(
263 *x1, *x2, block.derivative_options, dims1, dims2, scratch)
264 ? &scratch
265 : nullptr;
266 if (!covariance.buildCrossBlockDerivativesOnly(
267 *x1, *x2, block.derivative_options, dims1, dims2, scratch)) {
268 return nullptr;
269 }
270 return &scratch;
271}
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.
Definition SexpatCF.cpp:806
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 ...
Definition SexpatCF.cpp:931
Eigen::Matrix< Index_t, EigenDynamic, EigenDynamic, FieldMatrixStorage > FieldMatrixIdx
Definition Macros.h:29
bool buildCrossBlockDerivativesFactored(const FactoredTrainingGeometry &factors, Index_t block_n, Index_t block_m, uint8_t derivative_options, SexpatCF::CrossBlockGeometry &out)
bool shared_coordinates
Channel blocks carry the same Cartesian positions.
FactoredTrainingGeometry factors
streamed blocks come from here
std::shared_ptr< LazyFactoredTrainingGeometry > lazy_factors
std::vector< FieldMatrixd > x_loc_by_dim
indexed by dimension value

◆ rffFarthestPointOrder()

std::vector< int > gpr::rffFarthestPointOrder ( const Eigen::MatrixXd & positions)
nodiscard

Greedy maximin on squared Euclidean distance. Index 0 is first. A tie keeps the smaller index, so the order does not use a random generator.

Definition at line 235 of file RFFSelection.cpp.

236{
237 const int count = static_cast<int>(positions.rows());
238 std::vector<int> order;
239 order.reserve(static_cast<std::size_t>(std::max(count, 0)));
240 if (count <= 0 || !positions.allFinite()) return order;
241
242 std::vector<char> chosen(static_cast<std::size_t>(count), 0);
243 std::vector<double> nearest(static_cast<std::size_t>(count),
244 std::numeric_limits<double>::infinity());
245 int current = 0;
246 for (int placed = 0; placed < count; ++placed) {
247 if (current < 0) break;
248 order.push_back(current);
249 chosen[static_cast<std::size_t>(current)] = 1;
250 for (int candidate = 0; candidate < count; ++candidate) {
251 if (chosen[static_cast<std::size_t>(candidate)]) continue;
252 const double distance =
253 (positions.row(candidate) - positions.row(current))
254 .squaredNorm();
255 double& best = nearest[static_cast<std::size_t>(candidate)];
256 if (distance < best) best = distance;
257 }
258 current = -1;
259 double best = -1.0;
260 for (int candidate = 0; candidate < count; ++candidate) {
261 if (chosen[static_cast<std::size_t>(candidate)]) continue;
262 const double distance =
263 nearest[static_cast<std::size_t>(candidate)];
264 if (distance > best) {
265 best = distance;
266 current = candidate;
267 }
268 }
269 }
270 return order;
271}

◆ sha256File()

std::string gpr::sha256File ( const std::string & path)

Digest of a file's contents; empty when the file cannot be read.

Definition at line 134 of file Sha256.cpp.

135{
136 std::ifstream in(path, std::ios::binary);
137 if (!in) return {};
138 Hasher hasher;
139 std::vector<std::uint8_t> chunk(1 << 20);
140 while (in) {
141 in.read(reinterpret_cast<char*>(chunk.data()),
142 static_cast<std::streamsize>(chunk.size()));
143 hasher.update(chunk.data(), static_cast<std::size_t>(in.gcount()));
144 }
145 return in.eof() ? hasher.finish() : std::string();
146}

◆ sha256Hex()

std::string gpr::sha256Hex ( const void * data,
std::size_t size )

Lowercase hexadecimal SHA-256 digest of a byte range (FIPS 180-4).

Definition at line 127 of file Sha256.cpp.

128{
129 Hasher hasher;
130 hasher.update(static_cast<const std::uint8_t*>(data), size);
131 return hasher.finish();
132}

◆ stabilizePosteriorCovariance()

bool gpr::stabilizePosteriorCovariance ( Eigen::MatrixXd & covariance)
nodiscard

Project a rounded covariance onto the positive-semidefinite cone while preserving its nonnegative diagonal exactly.

Returns false for a non-square, non-finite or negative-diagonal input, when a correlation ratio is not finite, when a negative eigenvalue of that correlation exceeds the rounding tolerance, or when the correlation eigensolver fails. A smaller negative eigenvalue is projected away.

Definition at line 4368 of file StableBasis.cpp.

4369{
4370 if (covariance.rows() != covariance.cols() || !covariance.allFinite())
4371 return false;
4372 const Eigen::VectorXd diagonal = covariance.diagonal();
4373 if ((diagonal.array() < 0.0).any()) return false;
4374 if (covariance.rows() <= 1) return true;
4375
4376 // sqrt(d_i * d_j) overflows when both marginals are large even though
4377 // the geometric mean is finite. Scaling each square root keeps that
4378 // product inside the finite range.
4379 const auto geometric_mean = [](double left, double right) noexcept {
4380 if (!(left > 0.0) || !(right > 0.0)) return 0.0;
4381 return std::sqrt(left) * std::sqrt(right);
4382 };
4383
4384 // Finiteness and positive-semidefiniteness are decided before any clamp.
4385 // Clamping an overflowing ratio to +/-1, or dropping a large negative
4386 // eigenvalue, hides an input that is not a covariance. A negative
4387 // eigenvalue inside the backward-error allowance is the rounding of a
4388 // singular posterior; only that one is projected onto the PSD cone.
4389 // The grouped LOO ridge floors a near-null eigenvalue at scale*sqrt(eps),
4390 // so a retained block has cond <= 1/sqrt(eps). A cancelled correlation
4391 // entry is then wrong by at most cond*eps = sqrt(eps), measured on the
4392 // unit scale of a correlation. An entrywise perturbation of that size
4393 // has Frobenius norm at most n*sqrt(eps), and Weyl's inequality moves an
4394 // eigenvalue by at most that. The allowance is therefore
4395 // c*n*eps*||R|| with c = 1/sqrt(eps) and ||R|| = 1. A computed entry
4396 // outside [-1, 1] is the defect, so ||R|| does not grow with it. The
4397 // congruence by sqrt(diagonal) then preserves the cancellation-free
4398 // marginal variances.
4399 Eigen::MatrixXd correlation =
4400 Eigen::MatrixXd::Identity(covariance.rows(), covariance.cols());
4401 for (Eigen::Index column = 0; column < covariance.cols(); ++column) {
4402 for (Eigen::Index row = 0; row < column; ++row) {
4403 const double scale =
4404 geometric_mean(diagonal(row), diagonal(column));
4405 if (!std::isfinite(scale)) return false;
4406 double value = 0.0;
4407 if (!(scale > 0.0)) {
4408 if (covariance(row, column) != 0.0) return false;
4409 } else {
4410 value = covariance(row, column) / scale;
4411 if (!std::isfinite(value)) return false;
4412 }
4413 correlation(row, column) = value;
4414 correlation(column, row) = value;
4415 }
4416 }
4417 Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> solver(correlation);
4418 if (solver.info() != Eigen::Success) return false;
4419 const Eigen::VectorXd raw_eigenvalues = solver.eigenvalues();
4420 if (!raw_eigenvalues.allFinite()) return false;
4421 const double eps = std::numeric_limits<double>::epsilon();
4422 const double rows = static_cast<double>(correlation.rows());
4423 // ||R|| is the unit scale of a correlation, not the largest entry.
4424 constexpr double correlation_norm = 1.0;
4425 const double backward_constant = 1.0 / std::sqrt(eps);
4426 const double tolerance = backward_constant * rows * eps * correlation_norm;
4427 if (!std::isfinite(tolerance) ||
4428 !(raw_eigenvalues.minCoeff() >= -tolerance))
4429 return false;
4430 const Eigen::VectorXd eigenvalues = raw_eigenvalues.cwiseMax(0.0);
4431 correlation = solver.eigenvectors() * eigenvalues.asDiagonal() *
4432 solver.eigenvectors().transpose();
4433 const Eigen::VectorXd norm =
4434 correlation.diagonal().cwiseMax(0.0).cwiseSqrt();
4435 if ((norm.array() <= 0.0).any()) return false;
4436 for (Eigen::Index column = 0; column < covariance.cols(); ++column) {
4437 for (Eigen::Index row = 0; row < column; ++row) {
4438 const double norm_scale = norm(row) * norm(column);
4439 if (!(norm_scale > 0.0) || !std::isfinite(norm_scale)) return false;
4440 const double rho =
4441 std::clamp(correlation(row, column) / norm_scale, -1.0, 1.0);
4442 const double scale =
4443 geometric_mean(diagonal(row), diagonal(column));
4444 if (!std::isfinite(scale) || !std::isfinite(rho)) return false;
4445 covariance(row, column) = rho * scale;
4446 covariance(column, row) = covariance(row, column);
4447 if (!std::isfinite(covariance(row, column))) return false;
4448 }
4449 }
4450 covariance.diagonal() = diagonal;
4451 if (!covariance.allFinite()) return false;
4452 return true;
4453}

◆ subtractStableBasisProjectedCrossCovariance() [1/2]

bool gpr::subtractStableBasisProjectedCrossCovariance ( const StableBasisND & basis,
const Eigen::MatrixXd & Kstar,
const Eigen::MatrixXd & Kright,
const Eigen::MatrixXd & prior,
double total_sigma2,
Eigen::MatrixXd & K_post,
bool contracted_mean = false,
Eigen::Index left_queries = 1,
Eigen::Index right_queries = 1 )

Posterior cross covariance K(q, q') - k*^T (K + sigma2 I)^{-1} k*' on a stable basis. An in-range query cancels to a diagonal a few ulps of the prior diagonal from zero, the rounding of the basis column norms. For a self-covariance (&Kstar == &Kright and not a contracted mean), a negative diagonal cancellation residue is bounded by 2 * eps * local_scale. local_scale is abs(prior_ii) + abs(projected_ii) + abs(complement_ii): the absolute prior diagonal and the absolute values of the two subtracted terms. A column of n entries has a squared norm that rounds by about n*eps/2, so the raw diagonal can reach about n*eps*abs(prior). When that raw value lies within 3 times the bound, the subtraction returns the bound and keeps the sign. Cross-covariances and contracted means are left unclamped.

◆ subtractStableBasisProjectedCrossCovariance() [2/2]

bool gpr::subtractStableBasisProjectedCrossCovariance ( const StableBasisND & basis,
const EigenMatrix & Kstar,
const EigenMatrix & Kright,
const EigenMatrix & prior,
const double total_sigma2,
EigenMatrix & K_post,
bool contracted_mean,
Eigen::Index left_queries,
Eigen::Index right_queries )

Definition at line 103 of file Variance.cpp.

108{
109 const Eigen::MatrixXd& psi = basis.leftSingularVectors();
110 const Eigen::VectorXd& singular_values = basis.singularValues();
111 if (psi.rows() != Kstar.rows() || psi.cols() != singular_values.size() ||
112 Kright.rows() != Kstar.rows() || prior.rows() != Kstar.cols() ||
113 prior.cols() != Kright.cols())
114 return false;
115
116 // The covariance inverts the K + sigma2 I whose inverse gives the
117 // posterior weights, with sigma2 the likelihood variance plus the
118 // jitter; any other sigma2 gives the covariance of another posterior
119 // than the mean. The spectrum-derived condition floor raises sigma2
120 // only where machine precision cannot resolve the spectrum.
121 const double sigma2_eff = basis.conditionFlooredNoise(total_sigma2);
122 const Eigen::ArrayXd inv_projected =
123 (singular_values.array().square() + sigma2_eff).inverse();
124 // (K + sigma2 I)^-1 k* = Psi diag(1/(s^2 + sigma2)) Psi^T k*
125 // + w_c (k* - Psi Psi^T k*).
126 // The second term is the complement of the retained basis, weighted by
127 // w_c = 1/(s2_drop + sigma2) with s2_drop at least the resolution
128 // n eps s2_max, so it never exceeds the exact weight of a dropped
129 // component and the joint covariance stays positive semidefinite when
130 // sigma2 sits at the condition floor. Dropping it (range-only
131 // subtraction) left the training-row latent variance 1.66x the explicit
132 // posterior on the CuH2 fixture, because the complement carries the k*
133 // mass of the near-null directions that the noise alone resolves.
134 if (!(sigma2_eff > 0.0) || !std::isfinite(sigma2_eff)) return false;
135 if (contracted_mean) {
136 if (Kright.cols() != 1) return false;
137 // Both residual factors contribute (I - Psi Psi^T). Keeping the
138 // second projection also preserves the algebra when the computed
139 // singular vectors are not perfectly orthogonal.
140 const Eigen::VectorXd action = applyStableBasisStatisticalInverse(
141 basis, Kright.col(0), total_sigma2);
142 if (action.size() != Kstar.rows()) return false;
143 K_post = prior;
144 K_post.col(0).noalias() -= Kstar.transpose() * action;
145 return K_post.allFinite();
146 }
147 const bool same_operand = &Kstar == &Kright;
148 // A self covariance is a variance; the stable reduction forms it from
149 // the nonnegative eigenmode sums. Its diagonal is validated by the caller
150 // once the training-row identity has been applied. A cross covariance
151 // between different query sets has no sign to check.
152 if (linalg::stablePosteriorVarianceEnabled() && same_operand) {
153 K_post = basis.posteriorCovariance(Kstar, prior, total_sigma2);
154 return true;
155 }
156 // Range term Z^T D Z with Z = Psi^T k*, complement term w_c R^T R.
157 // The products are double GEMMs. A second projection puts an in-range
158 // query in the complement, so w_c does not turn one product rounding
159 // into a variance. What an in-range query then leaves on the diagonal
160 // is the rounding of the basis column norms, a few ulps of the prior.
161 const auto project = [&](const EigenMatrix& cross, Eigen::Index queries) {
162 EigenMatrix contrasts = cross;
163 const bool centered = queries > 1 && cross.cols() % queries == 0;
164 if (centered)
165 for (Eigen::Index first = 0; first < cross.cols(); first += queries)
166 contrasts.middleCols(first + 1, queries - 1).colwise() -=
167 contrasts.col(first);
168 EigenMatrix projected = psi.transpose() * contrasts;
169 EigenMatrix residual = contrasts - psi * projected;
170 residual.noalias() -= psi * (psi.transpose() * residual);
171 if (centered)
172 for (Eigen::Index first = 0; first < cross.cols();
173 first += queries) {
174 projected.middleCols(first + 1, queries - 1).colwise() +=
175 projected.col(first);
176 residual.middleCols(first + 1, queries - 1).colwise() +=
177 residual.col(first);
178 }
179 return std::make_pair(std::move(projected), std::move(residual));
180 };
181 const auto [Z, R] = project(Kstar, left_queries);
182 EigenMatrix right_Z, right_R;
183 if (!same_operand) {
184 auto projected = project(Kright, right_queries);
185 right_Z = std::move(projected.first);
186 right_R = std::move(projected.second);
187 }
188 const EigenMatrix& Z_other = same_operand ? Z : right_Z;
189 const EigenMatrix& R_other = same_operand ? R : right_R;
190 const EigenMatrix projected_term =
191 Z.transpose() * inv_projected.matrix().asDiagonal() * Z_other;
192 EigenMatrix posterior = prior;
193 posterior.noalias() -= projected_term;
194 const double w_c = basis.covarianceComplementWeight(sigma2_eff);
195 EigenMatrix complement_term;
196 if (w_c > 0.0) {
197 complement_term = w_c * (R.transpose() * R_other);
198 posterior.noalias() -= complement_term;
199 }
200 if (same_operand && !contracted_mean) {
201 for (Eigen::Index i = 0; i < posterior.rows() && i < posterior.cols();
202 ++i) {
203 // Preserve develop's negative-by-ulp behavior, but bound
204 // cancellation by the local subtraction magnitudes so
205 // sanitizer-only drift does not grow past a small multiple of the
206 // floating-point roundoff.
207 constexpr double kCancellationUlps = 2.0;
208 // Clang 18 + ASan can widen the cancellation residue to ~2.7 ulps
209 // while preserving the same sign and local scale, so allow a small
210 // sanitizer-only slack before capping at one roundoff unit.
211 constexpr double kCancellationSlack = 3.0;
212 const double local_scale =
213 std::abs(prior(i, i)) + std::abs(projected_term(i, i)) +
214 (w_c > 0.0 ? std::abs(complement_term(i, i)) : 0.0);
215 const double roundoff = kCancellationUlps *
216 std::numeric_limits<double>::epsilon() *
217 local_scale;
218 if (posterior(i, i) < 0.0 && roundoff > 0.0 &&
219 std::abs(posterior(i, i)) <= kCancellationSlack * roundoff) {
220 posterior(i, i) = std::max(posterior(i, i), -roundoff);
221 }
222 }
223 }
224 K_post = std::move(posterior);
225 return K_post.allFinite();
226}
Eigen::MatrixXd posteriorCovariance(const Eigen::MatrixXd &cross, const Eigen::MatrixXd &prior, double sigma2) const
Joint posterior covariance from the same exact eigenmode sums.
bool stablePosteriorVarianceEnabled() noexcept
Whether stable posterior variance reductions are enabled.
Definition ExactSchur.h:40
Eigen::VectorXd applyStableBasisStatisticalInverse(const StableBasisND &basis, const Eigen::VectorXd &rhs, double noise)
Definition Variance.cpp:82

◆ symmetrizeObservedInformation() [1/2]

bool gpr::detail::symmetrizeObservedInformation ( Eigen::MatrixXd & H)
inline

Definition at line 106 of file Helpers.h.

107{
108 if (H.rows() == 0 || H.rows() != H.cols() || !H.allFinite()) {
109 return false;
110 }
111 H = (0.5 * (H + H.transpose())).eval();
112 return H.allFinite();
113}

◆ symmetrizeObservedInformation() [2/2]

bool gpr::detail::symmetrizeObservedInformation ( Eigen::MatrixXd & H)
inline

Definition at line 106 of file Helpers.h.

107{
108 if (H.rows() == 0 || H.rows() != H.cols() || !H.allFinite()) {
109 return false;
110 }
111 H = (0.5 * (H + H.transpose())).eval();
112 return H.allFinite();
113}

◆ unpermuteMatrixRows()

EigenMatrix gpr::unpermuteMatrixRows ( const EigenMatrix & input,
const StructuredPermutation & p )
inline

Definition at line 245 of file PermutationUtils.h.

247{
248 EigenMatrix output(input.rows(), input.cols());
249 for (Index_t i = 0; i < static_cast<Index_t>(p.perm.size()); ++i)
250 output.row(p.perm[i]) = input.row(i);
251 return output;
252}

◆ unpermuteSymmetricMatrix()

EigenMatrix gpr::unpermuteSymmetricMatrix ( const EigenMatrix & input,
const StructuredPermutation & p )
inline

Definition at line 266 of file PermutationUtils.h.

268{
269 EigenMatrix output(input.rows(), input.cols());
270 for (Index_t i = 0; i < static_cast<Index_t>(p.perm.size()); ++i) {
271 for (Index_t j = 0; j < static_cast<Index_t>(p.perm.size()); ++j) {
272 output(p.perm[i], p.perm[j]) = input(i, j);
273 }
274 }
275 return output;
276}

◆ unpermuteVector()

Eigen::VectorXd gpr::unpermuteVector ( const Eigen::VectorXd & input,
const StructuredPermutation & p )
inline

Definition at line 227 of file PermutationUtils.h.

229{
230 Eigen::VectorXd output(input.size());
231 for (Index_t i = 0; i < static_cast<Index_t>(p.perm.size()); ++i)
232 output(p.perm[i]) = input(i);
233 return output;
234}

◆ useDenseFactorForTrace()

bool gpr::useDenseFactorForTrace ( bool prior_free_inverse,
bool use_hssvd_gradient,
bool distributed_factor,
long long factor_rows,
long long factor_cols,
long long target_size )
inline

Whether evaluateGradientWithGeometry may pass dense Cholesky factor L to the derivative trace contractions and appendLikelihoodNoiseGradient.

Prior-free Eigen fits use invC.trace() instead of L; HS-SVD Q-form gradients skip Cholesky decomposition so L may be absent or stale; ScaLAPACK/SLATE distributed fits must pass an empty factor so appendLikelihoodNoiseGradient selects the collective distributed trace.

Definition at line 34 of file PriorFreeInverse.h.

39{
40 return !prior_free_inverse && !use_hssvd_gradient && !distributed_factor &&
41 factor_rows == target_size && factor_cols == target_size &&
42 target_size > 0;
43}

◆ usesClassicJointEnergyForcePrior()

bool gpr::usesClassicJointEnergyForcePrior ( GPModelProfile profile)
inlinenodiscardnoexcept

Classic joint [E, F] inverse-distance profiles share the original Sexpat prior density (PriorSqrtt on magnSigma2, PriorGaussian on length scales, plus the packed-parameter log Jacobian).

Definition at line 206 of file Structures.h.

208{
209 return profile == GPModelProfile::CHEMGP ||
210 profile == GPModelProfile::GPRD_ZBL;
211}

◆ writeBMAOutput() [1/2]

void gpr::detail::writeBMAOutput ( const Eigen::VectorXd & flat,
Index_t N_im,
Index_t D,
Observation & image1 )
inline

Definition at line 184 of file Helpers.h.

186{
187 image1.E.resize(1, N_im);
188 image1.E = Eigen::Map<const Eigen::RowVectorXd>(flat.data(), N_im);
189 image1.G.resize(N_im, D);
190 image1.G = Eigen::Map<const Eigen::Matrix<double, Eigen::Dynamic,
191 Eigen::Dynamic, Eigen::ColMajor>>(
192 flat.data() + N_im, N_im, D);
193}
FieldMatrixd E

◆ writeBMAOutput() [2/2]

void gpr::detail::writeBMAOutput ( const Eigen::VectorXd & flat,
Index_t N_im,
Index_t D,
Observation & image1 )
inline

Definition at line 184 of file Helpers.h.

186{
187 image1.E.resize(1, N_im);
188 image1.E = Eigen::Map<const Eigen::RowVectorXd>(flat.data(), N_im);
189 image1.G.resize(N_im, D);
190 image1.G = Eigen::Map<const Eigen::Matrix<double, Eigen::Dynamic,
191 Eigen::Dynamic, Eigen::ColMajor>>(
192 flat.data() + N_im, N_im, D);
193}

◆ writePredictionVectorToObservation() [1/2]

void gpr::detail::writePredictionVectorToObservation ( const Observation & query,
const Eigen::VectorXd & values,
Observation & out )
inline

Definition at line 164 of file Helpers.h.

167{
168 const Index_t n = query.R.rows();
169 const Index_t D = query.R.cols();
170 out = query;
171 out.E.resize(1, n);
172 out.E = Eigen::Map<const Eigen::RowVectorXd>(values.data(), n);
173 out.G.resize(n, D);
174 out.G = Eigen::Map<const Eigen::Matrix<double, Eigen::Dynamic,
175 Eigen::Dynamic, Eigen::ColMajor>>(
176 values.data() + n, n, D);
177}

◆ writePredictionVectorToObservation() [2/2]

void gpr::detail::writePredictionVectorToObservation ( const Observation & query,
const Eigen::VectorXd & values,
Observation & out )
inline

Definition at line 164 of file Helpers.h.

167{
168 const Index_t n = query.R.rows();
169 const Index_t D = query.R.cols();
170 out = query;
171 out.E.resize(1, n);
172 out.E = Eigen::Map<const Eigen::RowVectorXd>(values.data(), n);
173 out.G.resize(n, D);
174 out.G = Eigen::Map<const Eigen::Matrix<double, Eigen::Dynamic,
175 Eigen::Dynamic, Eigen::ColMajor>>(
176 values.data() + n, n, D);
177}

Variable Documentation

◆ EigenDynamic

auto gpr::EigenDynamic = Eigen::Dynamic
constexpr

Definition at line 18 of file Macros.h.

◆ EigenMatrixStorage

auto gpr::EigenMatrixStorage = Eigen::StorageOptions::ColMajor
constexpr

Definition at line 19 of file Macros.h.

◆ FieldMatrixStorage

auto gpr::FieldMatrixStorage = Eigen::StorageOptions::RowMajor
constexpr

Definition at line 24 of file Macros.h.

◆ g_geom_build_seconds

double gpr::g_geom_build_seconds = 0.0

Definition at line 49 of file CovarianceAssembly.cpp.

◆ g_max_abs_alpha

double gpr::g_max_abs_alpha = 0.0

Definition at line 58 of file EnergyGradient.cpp.

◆ g_max_cond_k

double gpr::g_max_cond_k = 0.0

Definition at line 57 of file EnergyGradient.cpp.

◆ kDefaultChartScalarKernel

ChartScalarKernel gpr::kDefaultChartScalarKernel
inlineconstexpr
Initial value:

Definition at line 19 of file Matern52.h.

◆ kRFFEnergyNoiseFloor

double gpr::kRFFEnergyNoiseFloor = 1e-6
inlineconstexpr

Energy-channel floor used by the production random-feature model.

Definition at line 26 of file RFFFeatureSelection.h.

◆ kRFFFeaturesAuto

int gpr::kRFFFeaturesAuto = -1
inlineconstexpr

Sentinel stored in integer feature-count fields for the automatic rule.

Definition at line 35 of file RFFFeatureSelection.h.

◆ kRFFForceConvergenceTolerance

double gpr::kRFFForceConvergenceTolerance = 0.0514221
inlineconstexpr

Band force tolerance the random-feature error is not allowed to cross.

Definition at line 30 of file RFFFeatureSelection.h.

◆ kRFFGradientNoiseFloor

double gpr::kRFFGradientNoiseFloor = 1e-4
inlineconstexpr

Gradient-channel floor used by the production random-feature model.

Definition at line 28 of file RFFFeatureSelection.h.

◆ kRFFValidationMemoryCapBytes

std::uint64_t gpr::kRFFValidationMemoryCapBytes
inlineconstexpr
Initial value:
=
256ull * 1024ull * 1024ull

Exact validation Gram, and the D-by-D normal matrix, stay under this.

Definition at line 32 of file RFFFeatureSelection.h.

◆ sexpat_local_oracle_active

bool gpr::sexpat_local_oracle_active = false
thread_local

Thread-local switch for the local-oracle gradient region: when true the per-pair OpenMP pragma inside SexpatCF::calculateGradOfCov- MatrixWithDerivatives* activates. Set to true ONLY inside the SVGD per-particle oracle (which runs serial_per_rank=true with no MPI/ScaLAPACK collectives); SCG/MAP/Laplace paths leave it false so the distributed Cholesky doesn't get nested OMP teams that would oversubscribe the host.

Definition at line 35 of file SexpatCF.cpp.