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

#include <gpr/ml/GaussianProcessRegression.h>

Inheritance diagram for gpr::GaussianProcessRegression:

Classes

struct  ProfileSplitTotals
struct  MarginalLikelihoodReport
 Result of a prior-free negative log marginal-likelihood fit. More...
struct  ForceCalibrationReport
 Componentwise held-out force calibration in physical units. More...
struct  LeaveOneOutCalibrationReport
struct  AtomicEnvironmentParameterState
class  RefitTrustReport
struct  ActiveKernelEvidence
struct  PreparedHssvdHessianVector
class  HyperparameterPosterior
struct  LengthScaleTies
struct  LengthScaleFitState
struct  SecantQuadraticPriorState
struct  AnnealStageSummary
struct  ObjectivePlan
class  ActivePosteriorRestorePoint
struct  LaplaceTrainingCovarianceGeometry
struct  KrylovObjectiveState
struct  OptimizationObjectiveFrame
struct  ActivePosteriorState
struct  LaplacePosteriorStamp
struct  LaplacePosteriorSignature
struct  LaplacePosteriorState
struct  FittedHyperparameterDensity
struct  SliceLaplaceState
struct  OptimizerState

Public Types

enum class  MeasuredRowVerdict { Unmeasurable , Consistent , Contradicted }
 Agreement between measured rows and the current posterior. More...
enum class  LikelihoodNoiseVarianceUpdate { Invalid , Unchanged , Updated , Rebuilt }
enum class  MeanHessianProductStatus { Unavailable , Refused , Computed }
enum class  MixtureMeanHessianStatus { NotApplicable , Refused , Computed }
enum class  ObjectiveBackend { Auto , Dense , Krylov }
enum class  VarianceConvention { Predictive , Latent }
using MeanHessianAction
using MeanHessianPreparation

Public Member Functions

 GaussianProcessRegression ()
 GaussianProcessRegression (std::shared_ptr< const linalg::MpiCommunicator > communication)
virtual ~GaussianProcessRegression ()
linalg::MpiContext mpiContext () const
Eigen::VectorXd solveTrainingCovarianceInFactorLayout (const Eigen::VectorXd &rhs) const
void initialize (const InputParameters &parameters, const AtomsConfiguration &conf_info)
 Initialize GPR class.
bool initialized () const noexcept
void setConditionedHessian (const Eigen::VectorXd &point, const Eigen::MatrixXd &hessian)
void clearConditionedHessians () noexcept
bool findConditionedHessian (const Eigen::VectorXd &point, Eigen::MatrixXd &hessian_out) const
void setModelProfile (GPModelProfile profile)
GPModelProfile getModelProfile () const noexcept
void setAtomicEnvironmentModel (bool enabled)
bool atomicEnvironmentModelEnabled () const noexcept
bool atomicEnvironmentPosteriorBuilt () const
Eigen::Index atomicEnvironmentInducingCount () const
AtomicEnvironmentParameterState atomicEnvironmentParameterState () const
void restoreAtomicEnvironmentParameterState (const AtomicEnvironmentParameterState &state)
void setHyperparameters (const Observation &all_obs, const AtomsConfiguration &conf_info, const bool update_sexpat_cf_param=true, const bool update_const_cf_param=true, const bool update_sqrt_prior_param=true)
 Set up hyperparameters for GPR.
bool configureModeRefit (const Observation &oracle, const Coord &mode, double force_tolerance, ConvergenceNormType force_norm=ConvergenceNormType::L2_NORM)
bool configureMinimumModeRefit (const Observation &oracle, double force_tolerance, ConvergenceNormType force_norm=ConvergenceNormType::L2_NORM, const RefitTrustReport *trust_report=nullptr)
MeasuredRowVerdict measuredRowsAgreeWithPosterior (const Observation &rows, ConvergenceNormType force_norm, double *max_force_error=nullptr, double *max_force_sd=nullptr, double *evidence_nats=nullptr, double variance_calibration=1.0, RefitTrustReport *trust_report=nullptr)
void markHyperparametersFitted () noexcept
void setOptimizationRowPool (std::vector< bool > pool)
void clearOptimizationRowPool () noexcept
std::vector< std::size_t > holdLengthScalesUnresolvedBySubset (const Observation &subset)
 Hold, for the next fit, the length scales a pooled subset does not resolve: its inverse-distance features of that pair type span less than one length scale. Returns the held mask slots.
void setOptimizationRequiredRows (Coord positions)
void clearOptimizationRequiredRows () noexcept
void clearModeRefitHint () noexcept
void setActivePosteriorRefits (bool enabled) noexcept
bool activePosteriorRefitsEnabled () const noexcept
void setEnvironmentResiduals (bool enabled)
bool environmentResidualsEnabled () const noexcept
void setAdditivePairResiduals (bool enabled) noexcept
bool additivePairResidualsEnabled () const noexcept
const std::vector< ActiveKernelEvidence > & activeKernelEvidence () const noexcept
double activeFitStartForTesting () const noexcept
 MAP objective at the start of the last active correction fit.
Eigen::Index activeFitAnchorCountForTesting () const noexcept
Eigen::Index activeFitSupportCountForTesting () const noexcept
Eigen::Index residualInducingCount () const noexcept
Eigen::Index residualConfigurationCount () const noexcept
bool hasPendingActivePosteriorRefit () const noexcept
bool hasPendingResidualModelRefit () const noexcept
void setUpDefault ()
 Set up default parameters.
void evaluateTrainingCovarianceMatrix (const EigenMatrix &x, const Eigen::VectorXd &x_ind, EigenMatrix &cov_matrix, bool serial_per_rank=false, bool include_constant=true, bool include_noise=true)
 Evaluate training covariance matrix (gp_cov + noise covariance).
bool prepareTrainingKernelGeometry (const EigenMatrix &x, const Eigen::VectorXd &x_ind, TrainingKernelGeometry &out, bool reused=false) const
const TrainingKernelGeometry * fitGeometryFor (const EigenMatrix &x, const Eigen::VectorXd &x_ind) const
void releaseFitGeometry () const noexcept
std::size_t fitGeometryBuildsForTesting () const noexcept
bool evaluateTrainingCovarianceMatrixFromGeometry (const TrainingKernelGeometry &geom, const EigenMatrix &x, const Eigen::VectorXd &x_ind, EigenMatrix &cov_matrix, bool serial_per_rank=false, bool include_constant=true, bool include_noise=true)
bool evaluateActiveCovarianceFromGeometry (const TrainingKernelGeometry &geom, const Eigen::VectorXd &x_ind, const Eigen::VectorXd &theta, const std::vector< bool > &active_lengths, EigenMatrix &covariance, bool serial_per_rank=false, std::vector< EigenMatrix > *covariance_derivatives=nullptr)
bool evaluateActiveCovarianceFromGeometry (const TrainingKernelGeometry &geom, const Eigen::VectorXd &x_ind, const Eigen::VectorXd &theta, const std::vector< bool > &active_lengths, EigenMatrix &covariance, bool serial_per_rank, std::vector< EigenMatrix > *covariance_derivatives, const std::vector< Eigen::Index > &derivative_lengths)
bool contractActiveCovarianceDerivatives (const TrainingKernelGeometry &geom, const Eigen::VectorXd &x_ind, const Eigen::VectorXd &theta, const std::vector< bool > &active_lengths, const EigenMatrix &weight, const std::vector< Eigen::Index > &derivative_lengths, Eigen::VectorXd &contractions, bool serial_per_rank=false)
void evaluateEnergyAndGradientFromGeometry (const Eigen::VectorXd &w, const TrainingKernelGeometry &geom, const EigenMatrix &x, const Eigen::VectorXd &x_ind, const Eigen::VectorXd &y, EnergyAndGradient &energy_and_gradient)
void evaluateLeaveOneOutEnergyAndGradientFromGeometry (const Eigen::VectorXd &w, const TrainingKernelGeometry &geom, const EigenMatrix &x, const Eigen::VectorXd &x_ind, const Eigen::VectorXd &y, EnergyAndGradient &energy_and_gradient)
void evaluateLocalNeighborhoodLooEnergyAndGradientFromGeometry (const Eigen::VectorXd &w, const TrainingKernelGeometry &geom, const EigenMatrix &x, const Eigen::VectorXd &x_ind, const Eigen::VectorXd &y, EnergyAndGradient &energy_and_gradient)
double evaluateLocalNeighborhoodLooEnergy (const Eigen::VectorXd &w, const EigenMatrix &x, const Eigen::VectorXd &x_ind, const Eigen::VectorXd &y)
double evaluateLocalNeighborhoodLooGeometryTermForTesting (const Eigen::VectorXd &w, const EigenMatrix &x, const Eigen::VectorXd &x_ind, const Eigen::VectorXd &y, Eigen::Index geometry_index)
double evaluateEnergy (const Eigen::VectorXd &w, const EigenMatrix &x, const Eigen::VectorXd &x_ind, const Eigen::VectorXd &y)
bool evaluateGradientAfterEnergy (const Eigen::VectorXd &w, const EigenMatrix &x, const Eigen::VectorXd &x_ind, const Eigen::VectorXd &y, Eigen::VectorXd &gradient)
double evaluateEnergyFromGeometry (const Eigen::VectorXd &w, const TrainingKernelGeometry &geom, const EigenMatrix &x, const Eigen::VectorXd &x_ind, const Eigen::VectorXd &y)
bool evaluateGradientAfterEnergyFromGeometry (const Eigen::VectorXd &w, const TrainingKernelGeometry &geom, const EigenMatrix &x, const Eigen::VectorXd &x_ind, const Eigen::VectorXd &y, Eigen::VectorXd &gradient)
std::size_t trainingGeometryApplyCallsForTesting () const
bool evaluateTrainingCovarianceInFactorOrder (const EigenMatrix &x, const Eigen::VectorXd &x_ind, EigenMatrix &cov_matrix, bool include_noise=true)
bool evaluateTrainingCovarianceInFactorOrderFromGeometry (const TrainingKernelGeometry &geom, const EigenMatrix &x, const Eigen::VectorXd &x_ind, EigenMatrix &cov_matrix, bool include_noise=true)
std::size_t factorOrderAssembliesForTesting () const noexcept
bool evaluateTrainingCrossCovarianceInFactorOrder (const EigenMatrix &query, const Eigen::VectorXd &query_ind, EigenMatrix &cross) const
EigenMatrix trainingCrossCovarianceInFactorRows (const EigenMatrix &query, const Eigen::VectorXd &query_ind, bool serial_per_rank) const
std::size_t factorOrderCrossAssembliesForTesting () const noexcept
void evaluateHyperparameterObjectiveEnergyAndGradient (const Eigen::VectorXd &w, const EigenMatrix &x, const Eigen::VectorXd &x_ind, const Eigen::VectorXd &y, EnergyAndGradient &energy_and_gradient)
double computeObjectiveStationarityShiftNorm (const EigenMatrix &opt_R_matrix, const Eigen::VectorXd &opt_R_indices, const Eigen::VectorXd &opt_y, const Eigen::VectorXd &theta_reference, Eigen::VectorXd *shift_out=nullptr, double *energy_out=nullptr, Eigen::VectorXd *gradient_out=nullptr)
int lastRefitKind () const noexcept
double lastStationarityShift () const noexcept
double lastStationarityThreshold () const noexcept
int lastStationarityModel () const noexcept
bool refreshFullDataPosteriorIfObjectiveStationary (const Observation &full_observation, double *shift_norm_out=nullptr)
double computeLaplaceSkipScgShiftNorm (const EigenMatrix &opt_R_matrix, const Eigen::VectorXd &opt_R_indices, const Eigen::VectorXd &opt_y)
void evaluateCovarianceMatrix (const EigenMatrix &x1, const EigenMatrix &x2, const Eigen::VectorXd &x1_ind, const Eigen::VectorXd &x2_ind, EigenMatrix &C, bool serial_per_rank=false) const
 Evaluate covariance matrix between two input vectors.
void extractUniqueIndices (const Eigen::VectorXd &input_ind, Eigen::VectorXd &output_ind) const
 Extract unique indices from the input vector.
void evaluateEnergyAndGradient (const Eigen::VectorXd &w, const EigenMatrix &x, const Eigen::VectorXd &x_ind, const Eigen::VectorXd &y, EnergyAndGradient &energy_and_gradient)
 Evaluate the energy function (un-normalized negative marginal log posterior) and its gradient.
void optimize (const Observation &observation)
 Optimize paramaters of a Gaussian process.
MarginalLikelihoodReport optimizeMarginalLikelihood (const Observation &observation)
bool appendFixedHyperparameters (const Observation &full_observation)
Eigen::Index fullFitObservationCount () const noexcept
Eigen::Index fullFitCoordinateCount () const noexcept
ForceCalibrationReport calibrateHeldOutForces (const Observation &held_out, double nominal_probability)
LeaveOneOutCalibrationReport calibrateLeaveOneOut (double nominal_probability) const
LikelihoodNoiseVarianceUpdate setLikelihoodNoiseVariance (double physical_sigma2, const Observation *full_observation=nullptr)
 Set the likelihood noise variance in physical output units.
LikelihoodNoiseVarianceUpdate setLikelihoodNoiseVariance (double physical_sigma2, const Observation &full_observation)
bool applyLikelihoodNoiseVarianceFloor (double floor_sigma2, const Observation &full_observation)
 Raise the Gaussian likelihood noise variance to a floor.
void evaluatePriorMeanTargets (const Eigen::VectorXd &positions, double &energy, Eigen::VectorXd &gradient) const
 Prior-mean targets for a virtual (conditioning-only) observation at ~positions~.
void optimizeFactorized (const Observation &observation)
 Alternative optimization via eigendecomposition + noise grid search.
void optimizeChemistryFactorized (const Observation &observation)
 Chemistry-constrained ARD refit: pairtype lengthscale ratios fixed from descriptor spreads, global scale on a warm-centered log grid, (prefactor, noise) exact per grid point via the factorized likelihood. A handful of factorizations per refit instead of an SCG trajectory; ratio churn between refits is structurally impossible. Enabled by setChemFactorizedHyperparameters(true); degenerate descriptor scales fall back to the SCG core.
bool observationBandInfluence (const Observation &observation, const Coord &band_positions, Eigen::VectorXd &influence, bool collective=false)
 Per-observation influence on the band posterior.
bool observationBandInfluence (const Observation &observation, const Coord &band_positions, Eigen::VectorXd &influence, bool collective, const std::vector< char > &protected_rows, Eigen::VectorXd *removal_norm=nullptr)
void setChemFactorizedHyperparameters (bool enabled) noexcept
void setPhysicsCollocationPath (const Coord &path_points)
 Physics collocation set for hyperparameter selection: the live band (discrete IRC). When nonempty, the chem-factorized grid rejects hyperparameters whose posterior energy profile along these points oscillates (total variation beyond a scale-free multiple of the profile range), a constrained empirical-Bayes filter in the physics-informed-GP sense. Empty clears the filter.
bool getChemFactorizedHyperparameters () const noexcept
void calculatePotential (Observation &image1)
 Calculate potential within GPR model.
bool calculateMeanHessianVectorHssvd (const Coord &R, const Eigen::VectorXd &direction, Eigen::VectorXd &hessian_vector) const
bool calculateMeanHessianVectorDispatched (const Coord &R, const Eigen::VectorXd &direction, Eigen::VectorXd &hessian_vector)
MixtureMeanHessianStatus calculateLaplaceMixtureMeanHessianVector (const Coord &R, const Eigen::VectorXd &direction, Eigen::VectorXd &hessian_vector)
MeanHessianAction prepareMeanHessian (const Coord &R)
 Linear action of the physical posterior mean at one geometry.
bool calculateMeanHessian (const Coord &R, Eigen::MatrixXd &hessian)
 Dense Hessian of the physical posterior mean at one geometry.
bool calculateExactDirectionalCurvature (const Coord &R, const Eigen::VectorXd &direction, double &curvature)
MeanHessianAction prepareAnalyticMeanHessian (const Coord &R)
bool prepareMeanHessianVectorHssvd (const Coord &R, PreparedHssvdHessianVector &prepared) const
bool applyMeanHessianVectorHssvd (const PreparedHssvdHessianVector &prepared, const Eigen::VectorXd &direction, Eigen::VectorXd &hessian_vector) const
bool applyMeanHessianBlockHssvd (const PreparedHssvdHessianVector &prepared, const Eigen::MatrixXd &directions, Eigen::MatrixXd &hessian_block) const
void calculatePotentialLaplace (Observation &image1)
 Laplace-mixture-mean potential prediction (INLA, Rue et al. 2009).
void calculatePotentialLaplaceSlice (Observation &image1)
void calculateVarianceLaplaceSlice (Observation &image1)
void setUncertaintyMode (UncertaintyMode mode)
UncertaintyMode getUncertaintyMode () const
HyperparameterPosterior retainHyperparameterPosterior ()
HyperparameterPosterior currentHyperparameterPosterior () const
 Retain an existing, current quadrature without estimating a new one.
bool conditionOnHyperparameterPosterior (const HyperparameterPosterior &posterior)
void setUseAlphaKPredictMean (bool use) noexcept
 Enable the alpha-K contraction for MAP mean prediction.
bool getUseAlphaKPredictMean () const noexcept
void setUseAlphaKLaplaceMean (bool use) noexcept
 Enable the alpha-K contraction for Laplace-mixture mean prediction.
bool getUseAlphaKLaplaceMean () const noexcept
void setLaplaceSkipScgThreshold (double threshold) noexcept
double getLaplaceSkipScgThreshold () const noexcept
void setObjectiveStationaritySkipThreshold (double threshold) noexcept
double getObjectiveStationaritySkipThreshold () const noexcept
void setObjectiveStationaritySkipAuto (bool use) noexcept
void setFitStepStop (bool use) noexcept
 Whether the auto stationarity mode also ends each fit at its scale.
bool getObjectiveStationaritySkipAuto () const noexcept
bool objectiveStationaritySkipMayBeActive () const noexcept
bool usesFullObservationForHyperparameterOptimization (const Observation &observation) const noexcept
double objectiveStationaritySkipThresholdForTesting (const Eigen::VectorXd &theta_reference) const noexcept
bool hasObjectiveStationarityHessianForTesting () const noexcept
bool hasObjectiveStationarityInverseHessianForTesting () const noexcept
void setObjectiveStationarityHessianCholForTesting (const Eigen::MatrixXd &U)
void setObjectiveStationarityInverseHessianForTesting (const Eigen::MatrixXd &H_inverse)
void setObjectiveStationarityBbInverseScaleForTesting (Eigen::Index dimension, double inverse_scale)
void setSliceLaplaceHessianCholForTesting (const Eigen::MatrixXd &U)
void setUseTrainingGeometryHandle (bool use) noexcept
bool getUseTrainingGeometryHandle () const noexcept
void setProfilePredictMean (bool enabled) noexcept
bool getProfilePredictMean () const noexcept
void setProfileEnergySplit (bool enabled) noexcept
bool getProfileEnergySplit () const noexcept
void setProfileGradientSplit (bool enabled) noexcept
bool getProfileGradientSplit () const noexcept
const ProfileSplitTotals & profileSplitTotals () const noexcept
void resetProfileSplitTotals () noexcept
void logProfileSplitSummary ()
void setHutchinsonProbes (int num_probes) noexcept
int getHutchinsonProbes () const noexcept
void setHssvdBackend (bool enabled) noexcept
bool getHssvdBackend () const noexcept
void setRigidNullDeflation (bool enabled)
 Opt-in rigid-motion nullspace deflation for free systems.
bool rigidNullDeflationEnabled () const noexcept
const RigidDeflationDiagnostic & rigidDeflationDiagnostic () const noexcept
bool hasReusableHssvdPosterior () const noexcept
void setHssvdObjectiveContractions (bool enabled) noexcept
bool getHssvdObjectiveContractions () const noexcept
void setHssvdDualChopTolerance (double tol) noexcept
double getHssvdDualChopTolerance () const noexcept
void setHssvdDualRandomizedSketch (int sketch_size) noexcept
int getHssvdDualRandomizedSketch () const noexcept
void setHssvdDualLapackRrr (bool enabled) noexcept
bool getHssvdDualLapackRrr () const noexcept
void setHssvdLocalActiveSetSize (int size) noexcept
int getHssvdLocalActiveSetSize () const noexcept
void setHssvdLocalPosteriorActiveSetSize (int size) noexcept
int getHssvdLocalPosteriorActiveSetSize () const noexcept
void setMapMeanKernelForTesting (std::shared_ptr< const KernelOperator > kernel)
 Install the kernel used as the MAP mean expansion.
void setMapMeanKernelOverridesHssvdForTesting (bool override) noexcept
 Make an installed MAP test kernel take precedence over HS-SVD.
bool installActivePosteriorHessianActionsForTesting (MeanHessianPreparation background, bool background_exact, MeanHessianPreparation residual, bool residual_exact)
 Replace the active posterior's Hessian actions for one test.
void resetHssvdHessianVectorCallsForTesting () const noexcept
void setHssvdHessianBlockApplyFailsForTesting (bool fail) const noexcept
 Make the dense HS-SVD block apply fail for one test.
std::size_t getHssvdHessianVectorCallsForTesting () const noexcept
void resetDispatchedMapMeanHessianActionsForTesting () const noexcept
 Reset the count of exact MAP Hessian actions built by dispatch.
std::size_t getDispatchedMapMeanHessianActionsForTesting () const noexcept
 Count of exact MAP Hessian actions built by dispatch.
void setDisableOutputNormalization (bool d) noexcept
void setPriorMeanStatistic (PriorMeanStatistic statistic) noexcept
PriorMeanStatistic priorMeanStatistic () const noexcept
bool getDisableOutputNormalization () const noexcept
void setOutputScaleFloor (bool enabled) noexcept
bool outputScaleFloor () const noexcept
void synchronizeOutputTransformFrom (const GaussianProcessRegression &source)
void restoreOutputTransform (double mean, double scale, bool frozen_mean)
 Restore output coordinates alongside a kernel represented in them.
double outputMean () const noexcept
double outputScale () const noexcept
bool outputMeanFrozen () const noexcept
void setPopulationPrior (priors::PopulationPrior prior)
const priors::PopulationPrior & populationPrior () const noexcept
void applyPopulationPrior (const AtomsConfiguration &conf_info, const Eigen::VectorXd &ls_k, double own_s2_log)
void setUseLsPrior (bool use) noexcept
bool getUseLsPrior () const noexcept
void setUseLogNormalMagnPrior (bool use) noexcept
bool useLogNormalMagnPrior () const noexcept
void setLengthScaleSeedChemicalFloor (bool enabled) noexcept
bool getLengthScaleSeedChemicalFloor () const noexcept
void setRobustNu (double nu) noexcept
double robustNu () const noexcept
bool updateRobustRowWeights (const Observation &full_observation)
const Eigen::VectorXd & robustResidualNormsForTesting () const noexcept
const Eigen::VectorXd & robustExtraNoiseForTesting () const noexcept
LengthScaleFitState lengthScaleFitState () const
void restoreLengthScaleFitState (const LengthScaleFitState &state)
void configureLengthScaleTies (const AtomsConfiguration &configuration)
const LengthScaleTies & lengthScaleTies () const noexcept
void setLengthScaleTies (bool enabled)
void releaseLengthScaleTieForTesting (Index_t member)
int lastTieScreenProbes () const noexcept
bool lastTieScreenUsedHessianVector () const noexcept
const std::vector< double > & lastTieScreenCurvatures () const noexcept
bool lengthScaleTiesActive (Eigen::Index length_count) const noexcept
void tieLengthScaleParameters (Eigen::VectorXd &theta) const
 Sets every tied member to its leader's log length (theta(1 + t)).
void poolDescriptorScaleByTies (Eigen::VectorXd &scales) const
void reduceTiedLengthScaleGradient (Eigen::VectorXd &gradient) const
void refreshLengthScaleLeaders ()
 Recomputes the leaders from the released flags.
void setPairLocalTiles (bool enabled) noexcept
bool pairLocalTilesEnabled () const noexcept
void setPairLocalDirectionalTiles (bool enabled) noexcept
void setPrincipledNugget (bool use)
bool getPrincipledNugget () const noexcept
void setKappaMax (double kappa_max) noexcept
double getKappaMax () const noexcept
void setUseZBLPriorMean (bool use)
bool getUseZBLPriorMean () const noexcept
void setUseFFPriorMean (bool use)
void setSecantQuadraticPrior (const Eigen::VectorXd &position, const Eigen::VectorXd &gradient, const Eigen::MatrixXd &hessian, double reference_energy)
void clearSecantQuadraticPrior () noexcept
SecantQuadraticPriorState retainSecantQuadraticPrior () const
void restoreSecantQuadraticPrior (const SecantQuadraticPriorState &state)
bool physicalPriorMeanActive () const noexcept
 True when the ZBL or Morse prior mean is the one evaluation uses.
bool samplePhysicalPriorMean (const Eigen::VectorXd &position, double &energy, Eigen::VectorXd &gradient) const
const Eigen::MatrixXd & secantQuadraticHessian () const
void addLayeredPriorHessianAction (const Eigen::VectorXd &position, const Eigen::VectorXd &direction, Eigen::VectorXd &action) const
 H_prior(x) v + H_q v, with either term absent when that mean is off.
int secantQuadraticPriorUses () const noexcept
bool secantQuadraticPriorActive () const noexcept
bool getUseFFPriorMean () const noexcept
void setLogTrainingGeometry (bool enabled) noexcept
bool getLogTrainingGeometry () const noexcept
void setLogRankBlockCholesky (bool enabled) noexcept
bool getLogRankBlockCholesky () const noexcept
void setScalapackBlockSize (int block_size) noexcept
int getScalapackBlockSize () const noexcept
void setScalapackNprow (int nprow) noexcept
int getScalapackNprow () const noexcept
void setCutlassPluginPath (std::string path)
const std::string & getCutlassPluginPath () const noexcept
void setUsePsisLaplace (bool use) noexcept
bool getUsePsisLaplace () const noexcept
void setUsePsisDeterministicGrid (bool use) noexcept
bool getUsePsisDeterministicGrid () const noexcept
void setUseDeltaMethod (bool use) noexcept
bool getUseDeltaMethod () const noexcept
void setDeltaUHMinDiag (double v) noexcept
double getDeltaUHMinDiag () const noexcept
void setDeltaMaxRatio (double v) noexcept
double getDeltaMaxRatio () const noexcept
void buildRFFModel (const Observation &training_data, int D_rff)
void calculatePotentialRFF (Observation &image)
void calculateVarianceRFF (Observation &image)
int getRFFFeatures () const noexcept
bool isRFFBuilt () const noexcept
void setRFFFeaturesRequested (int D_rff)
int getRFFFeaturesRequested () const noexcept
void enableRFFFeatureSelection (double force_tol_fraction=0.0)
bool rffFeatureSelectionAuto () const noexcept
double rffForceTolFraction () const noexcept
RFFFeatureSelection selectRFFFeatures (const Observation &observation, std::uint64_t memory_cap_bytes=kRFFValidationMemoryCapBytes)
const RFFFeatureSelection & rffFeatureSelection () const noexcept
void setHyperparameterOptimizationMode (HyperparameterOptimizationMode mode) noexcept
void setRgminMethod (rgmin_method_t m) noexcept
void setVarianceSubsetConfigurations (int configurations) noexcept
void setVarianceSubsetFootprint (bool enabled) noexcept
bool varianceSubsetFootprint () const noexcept
void setVarianceSubsetConfigurationIds (std::vector< int > ids)
const std::vector< int > & varianceSubsetConfigurationIds () const noexcept
std::size_t varianceSubsetQueriesForTesting () const noexcept
std::size_t varianceSubsetFactorizationsForTesting () const noexcept
void setAnnealStage (bool enabled, std::size_t budget, std::size_t replicas, std::size_t every, std::uint64_t seed)
void noteSurrogateContradiction () noexcept
const AnnealStageSummary & lastAnnealStage () const noexcept
 The last stage that ran, for diagnostics and tests.
std::size_t lastFitEvaluationsForTesting () const noexcept
 Objective evaluations of the last hyperparameter fit.
std::size_t rgminWarmStartsForTesting () const noexcept
 Fits the rgmin sessions opened with the previous fit's record.
std::size_t rgminWarmPairsForTesting () const noexcept
 Curvature pairs the last rgmin fit transplanted from that record.
void setRgminWarmStart (bool keep) noexcept
void forgetRgminSessions () noexcept
HyperparameterOptimizationMode getHyperparameterOptimizationMode () const noexcept
const char * getHyperparameterOptimizerBackend () const noexcept
void setHyperparameterObjectiveMode (HyperparameterObjectiveMode mode) noexcept
HyperparameterObjectiveMode getHyperparameterObjectiveMode () const noexcept
virtual bool exactNlmlHessianVectorAvailable () const noexcept
bool nlmlHessianVectorCurvatureRequested () const noexcept
int nlmlHessianVectorFallbacks () const noexcept
void noteNlmlHessianVectorFallback (const char *where, const char *why)
void setOptimizationSubsetHistory (int rows) noexcept
int getOptimizationSubsetHistory () const noexcept
void setSubsetFailureEscalation (bool enabled) noexcept
bool subsetFailureEscalation () const noexcept
void setRgminInitialLogMove (double distance) noexcept
double rgminInitialLogMove () const noexcept
void setRgminInitialLogMoveWholeSession (bool whole_session) noexcept
void setSkipUnchangedSubsetFit (bool enabled) noexcept
bool skipUnchangedSubsetFit () const noexcept
std::size_t unchangedSubsetFitSkipsForTesting () const noexcept
 Fits skipped because the subset and the theta were unchanged.
std::size_t lastFitConfigurationsForTesting () const noexcept
bool lastWarmStartInfeasible () const noexcept
Eigen::VectorXd fittedKernelParameters () const
void setHyperparameterActiveMaskForTesting (const std::vector< bool > &mask)
void setScgMaxIterationsForTesting (Index_t max_iter) noexcept
void setWallClockLimit (std::shared_ptr< const WallClockLimit > limit)
bool wallClockLimitReached () const
 Collective on the model's process group for distributed fitters.
void setResidualDiagonalCorrectionForTesting (bool use, double eps) noexcept
void setNlmlHessianVectorFailureForTesting (bool fail) noexcept
void setScgDampingLimitForTesting (double limit) noexcept
void setFitTolerancesForTesting (double objective, double step) noexcept
void setObjectiveBackend (ObjectiveBackend backend, Eigen::Index rank=0)
void setObjectiveBackendForTesting (ObjectiveBackend backend, Eigen::Index rank=0)
ObjectiveBackend lastObjectiveBackend () const noexcept
ObjectivePlan objectivePlan () const noexcept
const linalg::linop::DenseResultCache & denseResultsForTesting () const noexcept
std::size_t gradientReplicatedInverseEntriesForTesting () const noexcept
double fitStepTolerance () const noexcept
bool lastScgFallbackUsedForTesting () const noexcept
bool scgStalledForTesting () const noexcept
void setRequireScgFallbackImprovement (bool enabled) noexcept
bool requiresScgFallbackImprovement () const noexcept
bool lastScgHitIterationBudgetForTesting () const noexcept
int lastFitIterations () const noexcept
int lastFitRestarts () const noexcept
 Restarts of the last fit; only a marginal-likelihood fit restarts.
const char * lastFitStopReason () const noexcept
void resetLaplacePosteriorSignatureBuildsForTesting () const noexcept
std::size_t laplacePosteriorSignatureBuildsForTesting () const noexcept
bool scaleLaplaceFactorForTesting (std::size_t index, double scale)
void setForceFactorOwnerLaplaceMeanForTesting (bool value) noexcept
bool disableLaplaceFactorsForTesting ()
void resetLaplaceMeanBlockPartitionCallsForTesting () const noexcept
std::size_t laplaceMeanBlockPartitionCallsForTesting () const noexcept
void resetIncrementalCholeskyCountersForTesting () const noexcept
void invalidateTrainingFactorCache ()
std::size_t incrementalCholeskyUpdatesForTesting () const noexcept
std::size_t fullCholeskyFactorizationsForTesting () const noexcept
std::size_t serialFactorReusesForTesting () const noexcept
bool devicePosteriorLiveForTesting () const noexcept
bool residentTrainingFactorRetainedForTesting () const noexcept
bool devicePosteriorCapableForTesting () const
EigenMatrix trainingCovarianceForTesting () const
std::size_t activeEnergyVarianceSolvesForTesting () const noexcept
std::size_t inverseDiagonalAppendsForTesting () const noexcept
std::size_t bandInfluenceFactorReusesForTesting () const noexcept
Eigen::VectorXd trainingInverseDiagonalForTesting () const
std::size_t inverseDiagonalBuildsForTesting () const noexcept
void resetHssvdAppendCountersForTesting () const noexcept
std::size_t hssvdAppendUpdatesForTesting () const noexcept
void resetHssvdFactorizationCountersForTesting () const noexcept
std::size_t hssvdFullFactorizationsForTesting () const noexcept
void resetFullDataRebuildCountersForTesting () const noexcept
std::size_t fullDataRebuildsForTesting () const noexcept
Eigen::Index hssvdBasisObservationCountForTesting () const noexcept
const StableBasisND & hssvdBasisForTesting () const noexcept
bool hssvdEnergyDesign (const FieldMatrixd &query, Eigen::VectorXd &design, Eigen::VectorXd &coeff) const
double hssvdBasisConditionNumberForTesting () const noexcept
double hssvdVarianceCalibrationFactorForTesting () const noexcept
void setHssvdVarianceCalibrationFactorForTesting (double factor) noexcept
void setOutputScaleForTesting (double scale) noexcept
void scaleTrainingVarianceToPhysical (Eigen::Ref< Eigen::VectorXd > variance) const
double totalPosteriorNoiseVarianceForTesting () const noexcept
bool hssvdLocalPosteriorCovarianceForTesting (const EigenMatrix &positions, const EigenMatrix &prior, EigenMatrix &K_post)
bool applyHssvdTrainingRowLatentVarianceForTesting (const EigenMatrix &positions, Eigen::VectorXd &variance, double total_sigma2) const
void applyHssvdTrainingRowLatentCovarianceForTesting (const EigenMatrix &positions, EigenMatrix &covariance, double total_sigma2) const
void setHssvdRetainedSpectrumForTesting (Eigen::MatrixXd psi, Eigen::VectorXd singular_values)
double reportedVarianceCalibrationFactor () const noexcept
bool hssvdObjectiveBasisValidForTesting () const
bool hssvdObjectiveTraceBasisMaterializedForTesting () const noexcept
Eigen::Index hssvdObjectivePendingReplicatedEntriesForTesting () const noexcept
double hssvdObjectiveConditionNumberForTesting () const
Eigen::Index hssvdObjectiveRankForTesting () const
double hssvdObjectiveTraceInvNoiseForTesting () const noexcept
const StructuredPermutation & trainingPermutationForTesting () const noexcept
bool hssvdObjectiveUsesDirectInverseForTesting () const noexcept
bool hssvdObjectiveTraceViaCholeskyForTesting () const noexcept
void resetLeaveOneOutObjectiveEvaluationsForTesting () const noexcept
std::size_t leaveOneOutObjectiveEvaluationsForTesting () const noexcept
void resetLocalLooObjectiveEvaluationsForTesting () const noexcept
std::size_t localLooObjectiveEvaluationsForTesting () const noexcept
Eigen::Index hssvdDualForceWeightRowsForTesting () const noexcept
Eigen::Index hssvdDualForceWeightColsForTesting () const noexcept
bool hssvdDualAlphaKPreparedForTesting () const noexcept
void resetDistributedHssvdDualKernelAssemblyCallsForTesting () const noexcept
std::size_t distributedHssvdDualKernelAssemblyCallsForTesting () const noexcept
void resetDistributedHssvdDualKernelFactorizationCallsForTesting () const noexcept
std::size_t distributedHssvdDualKernelFactorizationCallsForTesting () const noexcept
void setDescriptorPredictor (bool enabled) noexcept
void setVarianceConvention (VarianceConvention convention) noexcept
VarianceConvention varianceConvention () const noexcept
const char * hyperparameterOptimizationModeName () const noexcept
 Name of the hyperparameter fit in force, for the run report.
std::size_t lastInlaIterations () const noexcept
 Newton (RFO) iterations taken by the most recent INLA mode search.
void calculateInlaModeLogBoundsForTesting (const Eigen::VectorXd &theta_seed, double min_lengthscale, const EigenMatrix &x, const Eigen::VectorXd &y, Eigen::VectorXd &lower, Eigen::VectorXd &upper) const
double inlaMinimumLengthScaleForTesting (double range_x) const
bool computeInlaPosteriorModeForTesting (const EigenMatrix &x, const Eigen::VectorXd &x_ind, const Eigen::VectorXd &y, Eigen::VectorXd &theta_mode, const TrainingKernelGeometry *training_geom)
bool hssvdDualKernelActiveForTesting () const noexcept
bool assembleHssvdDualFullCrossCovarianceForTesting (const EigenMatrix &positions, EigenMatrix &Kstar) const
bool denseVariancePanelForTesting (const EigenMatrix &positions, EigenMatrix &whitened, Eigen::VectorXd &prior) const
 The whitened panel L^{-1} K(X, x*) and prior diagonal that the dense Cholesky marginal variance of positions reduces, built by the same assembly and triangular solve as calculateVariance.
bool assembleHssvdDualCrossCovarianceForTesting (const EigenMatrix &positions, EigenMatrix &Kstar, Eigen::VectorXd &prior_diag, bool energy_only) const
 The dual-kernel cross covariance and prior diagonal that the HS-SVD variance routes contract; energy_only selects the energy columns the energy gate reads.
bool assembleHssvdDualTrainingKernelForTesting (EigenMatrix &kernel) const
Eigen::Index hssvdLastLocalActiveSetConfigCountForTesting () const noexcept
Eigen::Index hssvdLastLocalActiveSetObservationCountForTesting () const noexcept
double hssvdLastLocalActiveSetConditionNumberForTesting () const noexcept
Eigen::Index hssvdLastLocalPosteriorConfigCountForTesting () const noexcept
Eigen::Index hssvdLastLocalPosteriorObservationCountForTesting () const noexcept
double hssvdLastLocalPosteriorConditionNumberForTesting () const noexcept
void resetDistributedTrainingCovarianceAssemblyCallsForTesting () const noexcept
std::size_t distributedTrainingCovarianceAssemblyCallsForTesting () const noexcept
void calculatePotentialDispatched (Observation &image1)
void calculatePotentialBatch (std::vector< Observation * > queries)
void calculateVarianceBatch (std::vector< Observation * > queries)
 One dispatched variance predict for B same-composition queries.
std::uint64_t factorEpoch () const noexcept
std::size_t varianceSolveCacheHitsForTesting () const noexcept
void calculateVarianceLaplace (Observation &image1)
void calculateVarianceDispatched (Observation &image1)
void calculateVarianceHssvd (Observation &image1)
void calculateObservationPosteriorCovariance (const EigenMatrix &positions, EigenMatrix &K_post, bool allow_hssvd_local=true)
Eigen::VectorXd calculateObservationNoiseDiagonal (const EigenMatrix &positions) const
std::optional< JointObservationVarianceReduction > calculateObservationForceVarianceReduction (const EigenMatrix &positions, Eigen::Index candidate_query, const std::vector< Eigen::Index > &target_queries, double noise_variance, bool allow_hssvd_local=true)
void calculateBackgroundObservationPosteriorCrossCovariance (const EigenMatrix &left, const EigenMatrix &right, EigenMatrix &covariance, const Eigen::VectorXd *mean_weights=nullptr)
double calculateObservationFunctionalVariance (const EigenMatrix &positions, const Eigen::VectorXd &weights)
bool conditionActivePosterior (const Observation &full_observation, std::shared_ptr< const KernelOperator > active_kernel={})
bool hasActivePosterior () const noexcept
Eigen::Index activePosteriorObservationCount () const noexcept
bool fitActivePosterior (const Observation &full_observation, const std::vector< bool > &active_lengths, bool compare_cartesian_residual=false)
bool refreshActivePosterior (const Observation &full_observation)
ActivePosteriorRestorePoint retainActivePosterior () const
bool restoreActivePosterior (const ActivePosteriorRestorePoint &point, const Observation &full_observation)
std::shared_ptr< const KernelOperator > makeActiveCovarianceOperator (const Eigen::VectorXd &theta, const std::vector< bool > &active_lengths) const
bool trainingFactorAppendable (Eigen::Index observations) const
std::size_t distributedFactorAppendsForTesting () const noexcept
 Rebuilds that appended to the cached distributed factor.
bool hasBeenOptimized () const
void setJitterSigma2 (double value)
 Set sigma2 jitter value.
double getJitterSigma2 () const noexcept
 Configured numerical diagonal jitter variance.
void setChainImageCount (int n)
void setLengthscaleFloor (double floor)
double getLengthscaleFloor () const noexcept
void setParameters (const GPRSetup &parameters)
 Set parameters of the GPR model.
LikGaussian & getLikGaussian ()
const LikGaussian & getLikGaussian () const
SexpatCF & getSexpAtCovarianceFunction ()
const SexpatCF & getSexpAtCovarianceFunction () const
void setInternalCoordinateChart (std::shared_ptr< const geometry::InternalCoordinateChart > chart, double length_scale)
void setGeodesicHeatPrior (std::shared_ptr< const GeodesicHeatEnergyForceKernel > kernel)
double fitGeodesicHeatPrior (const Coord &reference_path, const Observation &training_data)
void clearGeodesicHeatPrior ()
std::optional< double > inferInternalCoordinateLengthScale (const geometry::InternalCoordinateChart &chart) const
double getSigma2 () const noexcept
double getPhysicalTotalDiagonalRegularization () const noexcept
double likelihoodNoiseVariance () const noexcept
ConstantCF & getConstantCovarianceFunction ()
const ConstantCF & getConstantCovarianceFunction () const
Index_t getNumberOfPotentialCalls () const
const EigenMatrix & getL () const
bool hasTrainingCholeskyFactor (Eigen::Index expected_rows) const noexcept
bool parkTrainingCholeskyFactor ()
bool activateMaterializedPosterior ()
void claimActiveTrainingCholeskyFactor ()
 Associate the live ScaLAPACK factor with this GP after a materialize.
const Eigen::VectorXd & getAlpha () const
const EigenMatrix & getRMatrix () const noexcept
const Eigen::VectorXd & getRIndices () const noexcept
bool hasTrainingPermutation () const
EigenMatrix rowsInTrainingFactorLayout (const EigenMatrix &input) const
EigenMatrix symmetricMatrixInTrainingFactorLayout (const EigenMatrix &input) const
void setParameters (const Eigen::VectorXd &w)
 Set GP parameters. This function sets parameters in the covariance functions sexpat and constant and in the Gaussian likelyhood lik_gaussian.
Eigen::VectorXd packInlaHyperparameters () const
void setHierarchicalPrior (const Eigen::VectorXd &mu_log, double s2_log)
void clearHierarchicalPrior ()
bool assembleCompositeJointCovariance (const EigenMatrix &x, const Eigen::VectorXd &indices, SexpatCF &covariance, EigenMatrix &result) const
bool assembleCompositeJointCrossCovariance (const EigenMatrix &left, const EigenMatrix &right, const Eigen::VectorXd &left_indices, const Eigen::VectorXd &right_indices, SexpatCF &covariance, EigenMatrix &result) const
bool assembleCompositeJointCovarianceSecondDerivative (const EigenMatrix &x, const Eigen::VectorXd &indices, SexpatCF &covariance, const Eigen::VectorXd &direction, EigenMatrix &second) const
bool assembleCompositeJointCovarianceDerivatives (const EigenMatrix &x, const Eigen::VectorXd &indices, SexpatCF &covariance, std::vector< EigenMatrix > &derivatives) const
template<typename CovFunc>
void accumulateCrossCovarianceMatVecLocal (const EigenMatrix &x1, const EigenMatrix &x2, const Eigen::VectorXd &ind_Ddim, const Eigen::VectorXd &uDdim, const Eigen::VectorXd &ind_Ddim2, const Eigen::VectorXd &uDdim2, CovFunc &cov_func, const Eigen::VectorXd &weights, Eigen::VectorXd &output, bool do_reduce=true, bool select_prediction_product=false) const
 Accumulate local K(x1, x2)^T * weights contributions without materializing the full cross-covariance matrix.
void assembleDirectionalCovarianceDerivatives (const EigenMatrix &x, const Eigen::VectorXd &ind_Ddim, const Eigen::VectorXd &uDdim, const Eigen::VectorXd &direction, EigenMatrix &first, EigenMatrix &second, bool serial_per_rank=false) const
 Assemble the directional first and second derivatives of the training covariance matrix for the optimized Sexpat parameters.
bool assembleDirectionalCovarianceDerivativesFromGeometry (const TrainingKernelGeometry &geom, const EigenMatrix &x, const Eigen::VectorXd &ind_Ddim, const Eigen::VectorXd &uDdim, const Eigen::VectorXd &direction, EigenMatrix &first, EigenMatrix &second, bool serial_per_rank=false) const
std::optional< bool > tryPairLocalDirectionalCovariance (const TrainingKernelGeometry &geom, const Eigen::VectorXd &indices, const Eigen::VectorXd &direction, EigenMatrix &first, EigenMatrix &second, int rank=0, int ranks=1) const
double evaluateLocalLooGeometryTerm (const EigenMatrix &x, const Eigen::VectorXd &x_ind, const Eigen::VectorXd &y, const gpr::FieldMatrixd &geom_dist, Eigen::Index i, Eigen::Index n_geom, Eigen::Index n_blocks, double total_sigma2, Eigen::VectorXd *parameter_gradient=nullptr)
double evaluateLocalNeighborhoodLooObjective (const Eigen::VectorXd &w, const EigenMatrix &x, const Eigen::VectorXd &x_ind, const Eigen::VectorXd &y, Eigen::VectorXd *gradient)
bool failedOptim () const noexcept
std::size_t nonfiniteMarginalLikelihoodRejections () const noexcept
bool isDecomposedSuccessfully () const noexcept
const Observation & fittedObservations () const noexcept
 The observations the current posterior is fitted on.
void extractCoordinatesByIndex (const EigenMatrix &x, const Eigen::VectorXd &ind_Ddim, const Index_t ind, FieldMatrixd &x_loc) const
 Extract coordinates from x using value ind from ind_Ddim.
void assignBlockToMatrix (const Eigen::VectorXd &ind_Ddim1, const Eigen::VectorXd &ind_Ddim2, const Index_t row_val, const Index_t col_val, const FieldMatrixd &field, EigenMatrix &matrix, bool transpose_field=false) const
 Assign field to matrix according to indices form ind_Ddim1 and ind_Ddim2.
void accumulateBlockContribution (const Eigen::VectorXd &ind_Ddim1, const Eigen::VectorXd &ind_Ddim2, const Index_t row_val, const Index_t col_val, const FieldMatrixd &field, const EigenMatrix &invC, const Eigen::VectorXd &b, double &trace_accum, double &quad_accum, bool transpose_field=false, bool accumulate_quad=true, double diagonal_nugget=0.0, EigenMatrix *trace_sink=nullptr)
 Accumulate trace and quadratic-form contributions from one block.
double traceInverseProduct (const EigenMatrix &factor, const EigenMatrix &observation_order, const detail::RigidDeflationState *deflation_override=nullptr) const
 tr(K^{-1} A) through the training factor. A is in observation order.
void removeColumn (const Index_t column_ind, EigenMatrix &matrix)
 Remove column from the dense matrix.
Index_t getNumberOfRepetitiveIndices (const Eigen::VectorXd &ind_Ddim) const
 Count number of the first repetitive indices in ind_Ddim .
virtual void calculateVariance (Observation &image1)
 Compute predictive variance for energy and gradient. Corresponds to MATLAB get_variance.m.
bool tryGateEnergyVariance (const Observation &query, Eigen::RowVectorXd &energy_variance)
bool tryGateEnergyVarianceInterval (const Observation &query, Eigen::RowVectorXd &energy_variance_lower, Eigen::RowVectorXd &energy_variance_upper)
bool canCertifyEnergyVarianceInterval () const
bool tryBorderedNoiseReport (BorderedNoiseReport &report) const
virtual void refreshVariancePrefactor (const Eigen::VectorXd &)
 Hook called inside calculateVarianceLaplace at each CCD grid point, right after calculateMeanPrediction (so b := L^{-1} y is valid) and before calculateVariance(scratch_var). Purpose: let subclasses refresh any hyperparameter-dependent cached scalar that their override of calculateVariance consumes.
virtual double localVariancePrefactor (const Eigen::VectorXd &, const Eigen::VectorXd &) const
virtual double localVariancePrefactorFromQuadratic (const Eigen::VectorXd &, double) const
bool evaluateDirectionalCurvature (const Eigen::VectorXd &x_ind, const EigenMatrix &x, const Eigen::VectorXd &y, const Eigen::VectorXd &direction, double &curvature, const TrainingKernelGeometry *training_geom=nullptr)
 Evaluate the exact directional curvature p^T H p for the current GP objective state.
bool evaluateNlmlHessianVector (const Eigen::VectorXd &x_ind, const EigenMatrix &x, const Eigen::VectorXd &y, const Eigen::VectorXd &direction, Eigen::VectorXd &product, const TrainingKernelGeometry *training_geom=nullptr)
 Exact Hessian-vector product of the negative log marginal likelihood, including the covariance-function prior.
bool assembleExactHessian (const Eigen::VectorXd &x_ind, const EigenMatrix &x, const Eigen::VectorXd &y, int n_hyperparameters, Eigen::MatrixXd &H)
 Assemble the full p x p observed-information Hessian of the negative log marginal likelihood at the current hyperparameters.
bool assembleHessianInDirections (const Eigen::VectorXd &x_ind, const EigenMatrix &x, const Eigen::VectorXd &y, const Eigen::MatrixXd &directions, Eigen::MatrixXd &H)
bool fittedHyperparameterInformation (Eigen::MatrixXd &information, Eigen::MatrixXd &directions)
void setRetainFittedHyperparameterDensity (bool retain) noexcept
bool retainsFittedHyperparameterDensity () const noexcept
bool assembleExactHessianLocalDense (const Eigen::VectorXd &x_ind, const EigenMatrix &x, const Eigen::VectorXd &y, int n_hyperparameters, Eigen::MatrixXd &H)
void updateModelWithFullData (const Observation &full_observation)
void updateConfiguration (const AtomsConfiguration &conf_info)
 Update the internal atoms configuration. Use this when the set of active/frozen atoms changes dynamically.
void setUsePrecisionMatrix (bool use)
bool usePrecisionMatrix () const noexcept
const AtomsConfiguration & getAtomsConfig () const
void calculatePotentialSVGD (Observation &image1)
void calculateVarianceSVGD (Observation &image1)
void calculatePotentialBMA (Observation &image1)
void calculateVarianceBMA (Observation &image1)
void evaluateEnergyAndGradientLocal (const Eigen::VectorXd &w, const EigenMatrix &x, const Eigen::VectorXd &x_ind, const Eigen::VectorXd &y, EnergyAndGradient &energy_and_gradient)
void setSVGDConfig (const laplace::SteinVariationalConfig &cfg) noexcept
const laplace::SteinVariationalConfig & getSVGDConfig () const noexcept

Public Attributes

std::unique_ptr< SexpatCF > sexpat_cov_func

Protected Member Functions

void calculatePosteriorMeanPrediction ()
 Calculate posterior mean prediction w.r.t energy. This function mimics the following step from the MATLAB code: a = L'(L[E_all;G_all(:)]);.
void calculatePosteriorMeanPrediction (const Eigen::VectorXd &y)
void calculateMeanPrediction (const Eigen::VectorXd &y)
 Posterior mean prediction w.r.t energy. This function mimics the following step from the MATLAB code: b = L[E_all;G_all(:)];.
virtual void evaluateGradient (const EigenMatrix &x, const Eigen::VectorXd &x_ind, const Eigen::VectorXd &y, Eigen::VectorXd &gradient)
 Evaluate the gradient of energy (GP_E) for Gaussian Process.
void evaluateGradientWithGeometry (const EigenMatrix &x, const Eigen::VectorXd &x_ind, const Eigen::VectorXd &y, Eigen::VectorXd &gradient, const TrainingKernelGeometry *training_geom)
Eigen::Index covarianceParameterCount () const
bool currentThetaIncludesLikelihoodNoise () const noexcept
void prepareTrainingPermutation (const Eigen::VectorXd &x_ind)
void prepareTrainingPermutationLocal (const Eigen::VectorXd &x_ind)
EigenMatrix permuteTrainingRows (const EigenMatrix &input) const
Eigen::VectorXd permuteTrainingVector (const Eigen::VectorXd &input) const
Eigen::VectorXd unpermuteTrainingVector (const Eigen::VectorXd &input) const
std::pair< double, double > rigidNoiseDerivatives (const Eigen::VectorXd &direction) const
virtual double evaluateEnergy (const EigenMatrix &x, const Eigen::VectorXd &x_ind, const Eigen::VectorXd &y)
 Evaluate the energy function (un-normalized negative log marginal posterior).
virtual double hyperparameterDataTermScale () const
virtual void recordHyperparameterDataTerm (double, double)
virtual bool hyperparameterEnergyIsGaussian () const
bool decomposeCovarianceMatrix (const EigenMatrix &x, const Eigen::VectorXd &x_ind)
 Evaluate and decompose the covariance matrix using Cholesky decomposition.
bool decomposeForFittedTargets ()
 Factor the fitted design at the current hyperparameters and leave the posterior weights those of the fitted targets.
bool buildLaplaceTrainingCovarianceGeometry (const EigenMatrix &x, const Eigen::VectorXd &x_ind, LaplaceTrainingCovarianceGeometry &geometry) const
bool assembleLaplaceTrainingCovarianceFromGeometry (const LaplaceTrainingCovarianceGeometry &geometry, const Eigen::VectorXd &theta, EigenMatrix &cov_matrix) const
linalg::BackendContext & backend () const
linalg::linop::DenseCholeskySolver trainingSolver () const
void retainTrainingCholeskyFactor ()
void releaseTrainingKokkosFactor ()
void clearTrainingCholeskyFactor ()
bool canUseDevicePosterior () const
bool hasDevicePosterior () const noexcept
std::optional< double > conditionDevicePosterior (const EigenMatrix &rows, const Eigen::VectorXd &indices, const Eigen::VectorXd &targets, bool placeholder_targets=false)
bool devicePosteriorGradient (Eigen::VectorXd &gradient)
bool predictDevicePosterior (Observation &image, bool variance)
void refreshDeviceVarianceCalibration ()
void materializeDeviceFactor () const
void materializeDeviceAlpha () const
void planObjectiveBackend (const EigenMatrix &x, const Eigen::VectorXd &y)
 Update the plan from the dense factor just formed at this order.
std::optional< Eigen::VectorXd > krylovAddedDiagonal (const EigenMatrix &x)
std::optional< double > evaluateKrylovObjective (const Eigen::VectorXd &constant_update, const EigenMatrix &x, const Eigen::VectorXd &y)
void evaluateKrylovGradient (const EigenMatrix &x, const Eigen::VectorXd &x_ind, Eigen::VectorXd &gradient, const TrainingKernelGeometry *training_geom)
Eigen::VectorXd objectiveParameterStamp () const
Observation selectOptimizationSubset (const Observation &full_observation) const
 Select a hyperparameter-optimization subset via FPS-EMD.
std::vector< int > selectOptimizationSubsetRows (const Observation &full_observation) const
 Select a hyperparameter-optimization subset via FPS-EMD.
void captureFittedHyperparameterDensity (const Coord &positions, const Eigen::VectorXd &targets, const Eigen::VectorXd &theta, const funcmin::MapObjectiveConfig &penalty, double target_scale, bool use_ties)
OptimizationObjectiveFrame enterOptimizationObjectiveFrame (Eigen::VectorXd &targets, Eigen::Index energy_count, Eigen::VectorXd *theta)
void leaveOptimizationObjectiveFrame (const OptimizationObjectiveFrame &frame, Eigen::VectorXd *theta) noexcept
Eigen::VectorXd performHyperparameterOptimization (const Observation &opt_observation)
bool canUseTrainingGeometryObjective () const noexcept
void optimizeLaplaceINLA (const Observation &observation)
double inlaMaxLogMagnSigma2 (const EigenMatrix &x, const Eigen::VectorXd &y, const Eigen::VectorXd &theta_seed) const
void calculateInlaModeLogBounds (const Eigen::VectorXd &theta_seed, double min_lengthscale, double max_log_magn_sigma2, Eigen::VectorXd &lower, Eigen::VectorXd &upper) const
double inlaMinimumLengthScale (double range_x) const
bool computeInlaPosteriorMode (const EigenMatrix &x, const Eigen::VectorXd &x_ind, const Eigen::VectorXd &y, Eigen::VectorXd &theta_mode, const TrainingKernelGeometry *training_geom)
double evaluateEnergyLocalOnly (const Eigen::VectorXd &w, const EigenMatrix &x, const Eigen::VectorXd &x_ind, const Eigen::VectorXd &y)
bool monitorAndAdaptHyperparameters (const Eigen::VectorXd &new_parameters)
 Monitors hyperparameter history for oscillations and adapts the FPS history size.
void extendTrainingInverseDiagonal (Eigen::Index old_order, Eigen::Index new_order)
const Eigen::VectorXd & trainingInverseDiagonalInFactorLayout () const
Eigen::VectorXd trainingCholeskyDiagonal () const
virtual bool supportsRigidNullDeflation () const noexcept
Eigen::Index activeFactorOrder (Eigen::Index full_rows) const noexcept
bool tryDeflateFactorSignalCovariance (const EigenMatrix &x_ordered, const Eigen::VectorXd &ind_ordered, const Eigen::VectorXd &noise_ordered, double extra_uniform_noise, EigenMatrix &signal_cov, const Eigen::VectorXd &constant_update, Eigen::VectorXd &factor_constant, bool factor_order=true)

Static Protected Member Functions

static int chooseFarthestPointDeterministic (const std::vector< std::pair< int, double > > &candidate_distances, double tolerance=1e-12)
static bool computePairtypeDescriptorScale (const Coord &R, const AtomsConfiguration &conf_info, Eigen::VectorXd &ls_k)
 Per-pairtype motion scale rho0_k = sqrt(sum_f var(1/r_f)). Each pair feature is centered across configurations before summing its variance within InverseDistanceDescriptor::featurePairtypes groups. Units are inverse Angstrom. These scales seed SExpAt and anchor the MAP length-scale prior (MapObjectiveConfig::lengthscale_rho0).

Protected Attributes

bool is_training_cov_matrix_evaluated
bool is_decomposed_succesfully
bool use_precision_ = false
linalg::linop::DenseResultCache dense_results_
std::shared_ptr< const linalg::KokkosFactor > resident_training_factor_
std::shared_ptr< linalg::KokkosMolecularPosterior > device_posterior_
bool device_targets_placeholder_ = false
KrylovObjectiveState krylov_objective_
ObjectiveBackend objective_backend_override_ = ObjectiveBackend::Dense
EigenMatrix C
EigenMatrix L
Eigen::VectorXd b
Eigen::VectorXd a
EigenMatrix R_matrix
Eigen::VectorXd R_indices
StructuredPermutation training_permutation_
bool has_training_permutation_ = false
Eigen::VectorXd energy_and_gradient
std::deque< Eigen::VectorXd > hyperparameter_history_
const bool use_hod = true
const int monitoring_window_ = 5
const double flip_threshold_ = 0.8
const int history_increment_ = 2
const int max_history_ = 30
std::vector< bool > optimization_row_pool_
Coord optimization_required_positions_
Eigen::VectorXd training_inverse_diagonal_
bool use_rigid_null_deflation_ = false
bool serial_factor_rigid_deflation_enabled_ = false
detail::RigidDeflationState rigid_deflation_
RigidDeflationDiagnostic rigid_deflation_diag_

Friends

class tests::GaussianProcessRegressionTest
template<class Inner>
struct detail::TiedLengthScaleObjective
PublicLayoutBytes libraryPublicLayout ()
PublicLayoutBytes consumerPublicLayout ()

Detailed Description

Definition at line 335 of file GaussianProcessRegression.h.

Member Typedef Documentation

◆ MeanHessianAction

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

Definition at line 1255 of file GaussianProcessRegression.h.

◆ MeanHessianPreparation

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

Definition at line 1257 of file GaussianProcessRegression.h.

Member Enumeration Documentation

◆ LikelihoodNoiseVarianceUpdate

Enumerator
Invalid 
Unchanged 
Updated 
Rebuilt 

Definition at line 1048 of file GaussianProcessRegression.h.

1048 {
1049 Invalid,
1050 Unchanged,
1051 Updated,
1052 Rebuilt,
1053 };

◆ MeanHessianProductStatus

Outcome of one mean-Hessian source. Unavailable means another source may answer. Refused means this source owns the product and declines it. Computed means the product was written.

Enumerator
Unavailable 
Refused 
Computed 

Definition at line 1230 of file GaussianProcessRegression.h.

1230{ Unavailable, Refused, Computed };

◆ MeasuredRowVerdict

Agreement between measured rows and the current posterior.

Enumerator
Unmeasurable 
Consistent 
Contradicted 

Definition at line 512 of file GaussianProcessRegression.h.

512{ Unmeasurable, Consistent, Contradicted };

◆ MixtureMeanHessianStatus

Enumerator
NotApplicable 
Refused 
Computed 

Definition at line 1246 of file GaussianProcessRegression.h.

1246{ NotApplicable, Refused, Computed };

◆ ObjectiveBackend

Backend of the hyperparameter objective and gradient. Auto takes the Krylov backend when its operation count, planned from the pivot residual of the last dense factor at this training order, the noise floor and the fit tolerances, undercuts the dense factor.

Enumerator
Auto 
Dense 
Krylov 

Definition at line 2574 of file GaussianProcessRegression.h.

2574{ Auto, Dense, Krylov };

◆ VarianceConvention

Which posterior variance the model reports. Predictive is the classic get_variance.m definition (prior from the training covariance, so the likelihood nugget is included). Latent removes the likelihood diagonal and reports the variance of the latent function, the quantity an acquisition compares against the nugget; the stable-basis dual path always builds its prior from the kernel alone, so Latent makes every backend agree.

Enumerator
Predictive 
Latent 

Definition at line 2996 of file GaussianProcessRegression.h.

2996{ Predictive, Latent };

Constructor & Destructor Documentation

◆ GaussianProcessRegression() [1/2]

gpr::GaussianProcessRegression::GaussianProcessRegression ( )

Definition at line 97 of file GaussianProcessRegression.cpp.

98 : optimizer_state_(std::make_unique<OptimizerState>()),
99 backend_context_(std::make_shared<linalg::BackendContext>())
100{
101 hssvd_basis_ = StableBasisND(backend_context_);
102 sigma2 = 1e-7;
103 jitter_sigma2 = 1e-6;
104 optimization_alg = INLA_opt;
105 report_level = 0;
106
107 lik_gaussian = std::make_unique<LikGaussian>();
108 const_cov_fun = std::make_unique<ConstantCF>();
109 sexpat_cov_func = std::make_unique<SexpatCF>();
110
113 num_of_potential_calls = 0;
114 failedOptimizer = false;
115 fps_options.history = 5;
116 fps_options.latest_points = 2;
117 fps_options.metric = DistanceMetricType::EMD;
118 selectHyperparameterOptimizer(hyperparameter_optimization_mode_);
119}
@ INLA_opt
Definition Enums.h:30
std::unique_ptr< SexpatCF > sexpat_cov_func

◆ GaussianProcessRegression() [2/2]

gpr::GaussianProcessRegression::GaussianProcessRegression ( std::shared_ptr< const linalg::MpiCommunicator > communication)
explicit

Definition at line 206 of file GaussianProcessRegression.cpp.

209{
210 backend_context_ = std::make_shared<linalg::BackendContext>(communication);
211 rff_model_ = RFFModel(std::move(communication));
212 hssvd_basis_ = StableBasisND(backend_context_);
213}

◆ ~GaussianProcessRegression()

gpr::GaussianProcessRegression::~GaussianProcessRegression ( )
virtualdefault

Member Function Documentation

◆ accumulateBlockContribution()

void gpr::GaussianProcessRegression::accumulateBlockContribution ( const Eigen::VectorXd & ind_Ddim1,
const Eigen::VectorXd & ind_Ddim2,
const Index_t row_val,
const Index_t col_val,
const FieldMatrixd & field,
const EigenMatrix & invC,
const Eigen::VectorXd & b,
double & trace_accum,
double & quad_accum,
bool transpose_field = false,
bool accumulate_quad = true,
double diagonal_nugget = 0.0,
EigenMatrix * trace_sink = nullptr )

Accumulate trace and quadratic-form contributions from one block.

Adds the contribution of the logical block matrix(ind_Ddim1 == row_val, ind_Ddim2 == col_val) = field to trace_accum += tr(invC * dK_block) quad_accum += b^T dK_block b without materializing the full dK matrix.

Hutchinson option: when trace_probe_W and trace_probe_Z are supplied (both N x m), the trace term is accumulated as the un-normalized stochastic estimator sum_j (W_block.col(j))^T dK_block (Z_block.col(j)) instead of the exact tr(invC * dK_block). Summed over all blocks this gives sum_j w_j^T dK z_j; the caller divides the per-hyperparameter accumulator by m to obtain the Hutchinson estimate of tr(K^-1 dK) when w_j = K^-1 z_j. The quadratic (alpha / alpha-K) term is identical in both modes – only the trace term changes – so the estimator never perturbs the data-fit gradient.

Definition at line 2713 of file CovarianceAssembly.cpp.

2719{
2720 const EigenMatrix* trace_probe_W = hutch_trace_W_;
2721 const EigenMatrix* trace_probe_Z = hutch_trace_Z_;
2722 const EigenMatrix* hssvd_trace_basis = hssvd_trace_basis_;
2723 const EigenMatrix* hssvd_trace_weighted_basis = hssvd_trace_weighted_basis_;
2724 const auto row_block = observationChannelBlock(ind_Ddim1, row_val);
2725 const auto col_block = observationChannelBlock(ind_Ddim2, col_val);
2726 const Eigen::Index i_start = row_block.start;
2727 const Eigen::Index j_start = col_block.start;
2728 const Eigen::Index block_rows = row_block.count;
2729 const Eigen::Index block_cols = col_block.count;
2730
2731 const bool hutchinson =
2732 trace_probe_W != nullptr && trace_probe_Z != nullptr;
2733 const bool hssvd_trace =
2734 hssvd_trace_basis != nullptr && hssvd_trace_weighted_basis != nullptr &&
2735 (hssvd_trace_inv_noise_ > 0.0 || hssvd_trace_direct_inverse_) &&
2736 hssvd_trace_basis->rows() >= i_start + block_rows &&
2737 hssvd_trace_weighted_basis->rows() >= j_start + block_cols &&
2738 hssvd_trace_basis->cols() == hssvd_trace_weighted_basis->cols();
2739
2740 // Stochastic trace term: sum_j (W_block.col(j))^T field_block
2741 // (Z_block.col(j)) accumulated over blocks. With M = field_block *
2742 // Z_block (block_rows x m) this is the Frobenius inner product
2743 // <W_block, M>. The quadratic term below is byte-identical to the exact
2744 // path -- only the trace contribution is swapped.
2745 auto trace_probe_contrib = [&](const auto& field_block) -> double {
2746 const Eigen::Index m = trace_probe_W->cols();
2747 const auto W_block = trace_probe_W->block(i_start, 0, block_rows, m);
2748 const auto Z_block = trace_probe_Z->block(j_start, 0, block_cols, m);
2749 return (W_block.array() * (field_block * Z_block).array()).sum();
2750 };
2751
2752 auto hssvd_trace_contrib = [&](const auto& field_block) -> double {
2753 double diagonal_trace = 0.0;
2754 if (i_start == j_start && block_rows == block_cols) {
2755 diagonal_trace = field_block.trace();
2756 }
2757 const Eigen::Index rank = hssvd_trace_basis->cols();
2758 const auto U_block =
2759 hssvd_trace_basis->block(i_start, 0, block_rows, rank);
2760 const auto Urho_block =
2761 hssvd_trace_weighted_basis->block(j_start, 0, block_cols, rank);
2762 const double projected_trace =
2763 (U_block.array() * (field_block * Urho_block).array()).sum();
2764 if (hssvd_trace_direct_inverse_) return projected_trace;
2765 return hssvd_trace_inv_noise_ * (diagonal_trace - projected_trace);
2766 };
2767
2768 auto contract_block = [&](const auto& field_block) {
2769 if (trace_sink != nullptr) {
2770 trace_sink->block(i_start, j_start, block_rows, block_cols) =
2771 field_block;
2772 } else if (hssvd_trace) {
2773 trace_accum += hssvd_trace_contrib(field_block);
2774 } else if (hutchinson) {
2775 trace_accum += trace_probe_contrib(field_block);
2776 } else {
2777 const auto inv_block =
2778 invC.block(i_start, j_start, block_rows, block_cols);
2779 trace_accum += (inv_block.array() * field_block.array()).sum();
2780 }
2781 if (accumulate_quad) {
2782 const auto b_row = b.segment(i_start, block_rows);
2783 const auto b_col = b.segment(j_start, block_cols);
2784 quad_accum += b_row.dot(field_block * b_col);
2785 }
2786 };
2787
2788 auto accumulate_from_block = [&](const auto& field_block) {
2789 if (diagonal_nugget > 0.0 && i_start == j_start &&
2790 block_rows == block_cols) {
2791 EigenMatrix regularized = field_block;
2792 regularized.diagonal().array() +=
2793 diagonal_nugget * field_block.diagonal().array();
2794 contract_block(regularized);
2795 if (!accumulate_quad) {
2796 quad_accum += diagonal_nugget *
2797 (b.segment(i_start, block_rows).array().square() *
2798 field_block.diagonal().array())
2799 .sum();
2800 }
2801 } else {
2802 contract_block(field_block);
2803 }
2804 };
2805
2806 if (!transpose_field) {
2807 const auto field_block = field.block(0, 0, block_rows, block_cols);
2808 accumulate_from_block(field_block);
2809 } else {
2810 const auto field_block =
2811 field.block(0, 0, block_cols, block_rows).transpose();
2812 accumulate_from_block(field_block);
2813 }
2814}
Eigen::Matrix< double, EigenDynamic, EigenDynamic, EigenMatrixStorage > EigenMatrix
Definition Macros.h:20

◆ accumulateCrossCovarianceMatVecLocal()

template<typename CovFunc>
void gpr::GaussianProcessRegression::accumulateCrossCovarianceMatVecLocal ( const EigenMatrix & x1,
const EigenMatrix & x2,
const Eigen::VectorXd & ind_Ddim,
const Eigen::VectorXd & uDdim,
const Eigen::VectorXd & ind_Ddim2,
const Eigen::VectorXd & uDdim2,
CovFunc & cov_func,
const Eigen::VectorXd & weights,
Eigen::VectorXd & output,
bool do_reduce = true,
bool select_prediction_product = false ) const

Accumulate local K(x1, x2)^T * weights contributions without materializing the full cross-covariance matrix.

This follows the same block ownership scheme as applyCrossCovarianceFunction() but contracts each owned block directly against the relevant segment of weights.

Public so numerical-equivalence tests can call it via a helper free function without friend gymnastics; those tests gate alpha-K changes on bit-equivalence vs the dense KK^T * alpha reference.

Definition at line 347 of file GaussianProcessRegression.inl.

353{
354 const auto product_mode = select_prediction_product
356 : linalg::ProductMode::Compensated;
357 const auto contract = [&](const auto& matrix,
358 const Eigen::VectorXd& coefficients) {
359 Eigen::VectorXd result(matrix.cols());
360 for (Eigen::Index col = 0; col < matrix.cols(); ++col) {
361 const Eigen::VectorXd column = matrix.col(col);
362 result(col) = linalg::evaluateStoredProduct(
363 column.data(), coefficients.data(),
364 static_cast<int>(coefficients.size()), product_mode);
365 }
366 return result;
367 };
368 if constexpr (std::is_same<typename std::decay<CovFunc>::type,
369 SexpatCF>::value) {
370 EigenMatrix joint_covariance;
371 if (assembleCompositeJointCrossCovariance(x1, x2, ind_Ddim, ind_Ddim2,
372 cov_func, joint_covariance)) {
373 if (weights.size() != joint_covariance.rows()) {
374 throw std::invalid_argument(
375 "manifold covariance weights do not match joint rows");
376 }
377 output = contract(joint_covariance, weights);
378 return;
379 }
380 }
381
382 FieldMatrixd x1_loc_0, x2_loc_0, x1_loc_1, x2_loc_1;
383 FieldMatrixd C_temp;
384 FieldMatrixIdx dims1, dims2;
385 std::vector<FieldMatrixd> Kdf(1), Kdf2(1);
386
387 const detail::ObservationChannelLayout training_channels(ind_Ddim);
388 const detail::ObservationChannelLayout prediction_channels(ind_Ddim2);
389 if (!training_channels.valid() || !prediction_channels.valid() ||
390 ind_Ddim.size() != x1.rows() || ind_Ddim2.size() != x2.rows() ||
391 weights.size() != x1.rows())
392 throw std::invalid_argument(
393 "cross covariance channels have invalid shape");
394 Eigen::Index max_prediction_rows = prediction_channels.block(0).count;
395 for (Eigen::Index channel = 0; channel < uDdim2.size(); ++channel)
396 max_prediction_rows = std::max(
397 max_prediction_rows,
398 prediction_channels.block(static_cast<Index_t>(uDdim2(channel)))
399 .count);
400
401 output.resize(x2.rows());
402 output.setZero();
403 dims1.resize(1, 1);
404 dims2.resize(1, 1);
405
406 const Index_t total_blocks =
407 1 + static_cast<Index_t>(uDdim2.size()) +
408 static_cast<Index_t>(uDdim.size()) +
409 static_cast<Index_t>(uDdim.size() * uDdim2.size());
410 Eigen::MatrixXd block_contribs =
411 Eigen::MatrixXd::Zero(total_blocks, max_prediction_rows);
412 std::vector<Index_t> block_cols(static_cast<size_t>(total_blocks), 0);
413 std::vector<Index_t> block_sizes(static_cast<size_t>(total_blocks), 0);
414
415 auto assign_block_contrib = [&](const Index_t row_val,
416 const Index_t col_val,
417 const FieldMatrixd& field,
418 const Index_t block_idx,
419 const bool transpose_field = false) {
420 const auto row_block = training_channels.block(row_val);
421 const auto col_block = prediction_channels.block(col_val);
422 const Eigen::Map<const Eigen::VectorXd> weight_block(
423 weights.data() + row_block.start, row_block.count);
424
425 const auto matrix_block = !transpose_field ? field : field.transpose();
426 block_contribs.row(block_idx).head(col_block.count) =
427 contract(matrix_block, weight_block).transpose();
428 block_cols[static_cast<size_t>(block_idx)] = col_block.start;
429 block_sizes[static_cast<size_t>(block_idx)] = col_block.count;
430 };
431
432 Eigen::Map<const Eigen::ArrayXd> ind_Ddim_copy(ind_Ddim.data(),
433 ind_Ddim.size());
434 Eigen::Map<const Eigen::ArrayXd> ind_Ddim2_copy(ind_Ddim2.data(),
435 ind_Ddim2.size());
436
437#ifdef GPR_LINALG_SCALAPACK
438 auto& _mpi_st = backend().distributed();
439 _mpi_st.initialize();
440 const Index_t mpi_rank = static_cast<Index_t>(_mpi_st.myrank());
441 const Index_t mpi_np = static_cast<Index_t>(_mpi_st.nprocs());
442 const auto owns_block = [&](const Index_t block_idx) {
443 return !do_reduce || block_idx % mpi_np == mpi_rank;
444 };
445#else
446 (void)do_reduce;
447 const auto owns_block = [&](const Index_t) { return true; };
448#endif
449
450 x1_loc_0.resize((Index_t)(ind_Ddim_copy == 0).count(),
451 (Index_t)x1.cols() + 1);
452 x1_loc_0.setZero();
453 x2_loc_0.resize((Index_t)(ind_Ddim2_copy == 0).count(),
454 (Index_t)x2.cols() + 1);
455 x2_loc_0.setZero();
456
457 extractCoordinatesByIndex(x1, ind_Ddim, 0, x1_loc_0);
458 extractCoordinatesByIndex(x2, ind_Ddim2, 0, x2_loc_0);
459
460 Index_t block_idx = 0;
461 if ((ind_Ddim_copy == 0).count() > 0 && (ind_Ddim2_copy == 0).count() > 0) {
462 block_cols[static_cast<size_t>(block_idx)] = 0;
463 block_sizes[static_cast<size_t>(block_idx)] =
464 prediction_channels.block(0).count;
465 if (owns_block(block_idx)) {
466 cov_func.calculateCovarianceMatrix(x1_loc_0, x2_loc_0, C_temp);
467 assign_block_contrib(0, 0, C_temp, block_idx);
468 }
469 }
470 ++block_idx;
471
472 if ((ind_Ddim_copy == 0).count() > 0) {
473 for (Index_t i = 0; i < uDdim2.size(); ++i, ++block_idx) {
474 const Index_t pred_block = static_cast<Index_t>(uDdim2[i]);
475 block_cols[static_cast<size_t>(block_idx)] =
476 prediction_channels.block(pred_block).start;
477 block_sizes[static_cast<size_t>(block_idx)] =
478 prediction_channels.block(pred_block).count;
479 if (!owns_block(block_idx)) continue;
480
481 dims2(0, 0) = pred_block;
482 x2_loc_1.resize((Index_t)(ind_Ddim2_copy == pred_block).count(),
483 (Index_t)x2.cols() + 1);
484 x2_loc_1.setZero();
485 extractCoordinatesByIndex(x2, ind_Ddim2, pred_block, x2_loc_1);
486 cov_func.ginput4(x2_loc_1, x1_loc_0, dims2, Kdf);
487 assign_block_contrib(0, pred_block, Kdf[0], block_idx, true);
488 }
489 } else {
490 block_idx += static_cast<Index_t>(uDdim2.size());
491 }
492
493 if ((ind_Ddim2_copy == 0).count() > 0) {
494 for (Index_t i = 0; i < uDdim.size(); ++i, ++block_idx) {
495 const Index_t obs_block = static_cast<Index_t>(uDdim[i]);
496 block_cols[static_cast<size_t>(block_idx)] = 0;
497 block_sizes[static_cast<size_t>(block_idx)] =
498 prediction_channels.block(0).count;
499 if (!owns_block(block_idx)) continue;
500
501 dims1(0, 0) = obs_block;
502 x1_loc_1.resize((Index_t)(ind_Ddim_copy == obs_block).count(),
503 (Index_t)x1.cols() + 1);
504 x1_loc_1.setZero();
505 extractCoordinatesByIndex(x1, ind_Ddim, obs_block, x1_loc_1);
506 cov_func.ginput4(x1_loc_1, x2_loc_0, dims1, Kdf);
507 assign_block_contrib(obs_block, 0, Kdf[0], block_idx);
508 }
509 } else {
510 block_idx += static_cast<Index_t>(uDdim.size());
511 }
512
513 for (Index_t i = 0; i < uDdim.size(); ++i) {
514 const Index_t obs_block = static_cast<Index_t>(uDdim[i]);
515 dims1(0, 0) = obs_block;
516 x1_loc_1.resize((Index_t)(ind_Ddim_copy == obs_block).count(),
517 (Index_t)x1.cols() + 1);
518 x1_loc_1.setZero();
519 extractCoordinatesByIndex(x1, ind_Ddim, obs_block, x1_loc_1);
520 for (Index_t j = 0; j < uDdim2.size(); ++j, ++block_idx) {
521 const Index_t pred_block = static_cast<Index_t>(uDdim2[j]);
522 block_cols[static_cast<size_t>(block_idx)] =
523 prediction_channels.block(pred_block).start;
524 block_sizes[static_cast<size_t>(block_idx)] =
525 prediction_channels.block(pred_block).count;
526 if (!owns_block(block_idx)) continue;
527
528 dims2(0, 0) = pred_block;
529 x2_loc_1.resize((Index_t)(ind_Ddim2_copy == pred_block).count(),
530 (Index_t)x2.cols() + 1);
531 x2_loc_1.setZero();
532 extractCoordinatesByIndex(x2, ind_Ddim2, pred_block, x2_loc_1);
533 if (obs_block == pred_block) {
534 cov_func.ginput2(x1_loc_1, x2_loc_1, dims1, Kdf2);
535 } else {
536 cov_func.ginput3(x1_loc_1, x2_loc_1, dims1, dims2, Kdf2);
537 }
538 assign_block_contrib(obs_block, pred_block, Kdf2[0], block_idx);
539 }
540 }
541
542#ifdef GPR_LINALG_SCALAPACK
543 if (do_reduce && mpi_np > 1) {
544 // Each block_contribs row is written by exactly one owning
545 // rank: disjoint support, exact under Allreduce (see
546 // disjoint_sum_bcast).
547 backend().disjoint_sum_bcast(block_contribs.data(),
548 static_cast<int>(block_contribs.size()));
549 }
550 // disjoint_sum_bcast makes block_contribs bit-identical on every rank.
551 // block_cols is populated unconditionally per-rank at the top of the
552 // block loop, so the output assembles identically without an extra
553 // trailing MPI_Bcast(output) round-trip.
554#endif
555 for (Index_t idx = 0; idx < total_blocks; ++idx) {
556 const Index_t col_start = block_cols[static_cast<size_t>(idx)];
557 const Index_t count = block_sizes[static_cast<size_t>(idx)];
558 output.segment(col_start, count).noalias() +=
559 block_contribs.row(idx).head(count).transpose();
560 }
561}
linalg::BackendContext & backend() const
bool assembleCompositeJointCrossCovariance(const EigenMatrix &left, const EigenMatrix &right, const Eigen::VectorXd &left_indices, const Eigen::VectorXd &right_indices, SexpatCF &covariance, EigenMatrix &result) const
void extractCoordinatesByIndex(const EigenMatrix &x, const Eigen::VectorXd &ind_Ddim, const Index_t ind, FieldMatrixd &x_loc) const
Extract coordinates from x using value ind from ind_Ddim.
double evaluateStoredProduct(const double *left, const double *right, int length, ProductMode mode)
ProductMode productMode()
Eigen::Matrix< Index_t, EigenDynamic, EigenDynamic, FieldMatrixStorage > FieldMatrixIdx
Definition Macros.h:29
uint32_t Index_t
Definition Macros.h:17
Eigen::Matrix< double, EigenDynamic, EigenDynamic, FieldMatrixStorage > FieldMatrixd
Definition Macros.h:25

◆ activateMaterializedPosterior()

bool gpr::GaussianProcessRegression::activateMaterializedPosterior ( )

Reactivate a materialized posterior without rebuilding its joint energy-gradient covariance. Eigen factors and HS-SVD posteriors are already object-local; ScaLAPACK factors are restored into its solve slot.

Definition at line 313 of file Decompose.cpp.

314{
315 if (atomic_environment_model_) return atomicEnvironmentPosteriorBuilt();
316#ifdef GPR_LINALG_KOKKOS
318#endif
319 // The spectral background owns its factors even when an active correction
320 // contributes to prediction. Background-only curvature shortcuts still
321 // require hasReusableHssvdPosterior().
322 if (hasMaterializedHssvdBackground() || rff_replaces_exact_) return true;
323 if (!is_decomposed_succesfully || a.size() != R_matrix.rows()) {
324 return false;
325 }
327 return true;
328 }
329#ifdef GPR_LINALG_SCALAPACK
330 if (!training_cholesky_is_distributed_ ||
331 parked_training_cholesky_.order != R_matrix.rows()) {
332 return false;
333 }
334 auto snapshot = std::move(parked_training_cholesky_);
335 parked_training_cholesky_.clear();
336 return backend().distributed().restore_cached_L(std::move(snapshot), this);
337#else
338 return false;
339#endif
340}
bool hasDevicePosterior() const noexcept
bool hasTrainingCholeskyFactor(Eigen::Index expected_rows) const noexcept

◆ activeEnergyVarianceSolvesForTesting()

std::size_t gpr::GaussianProcessRegression::activeEnergyVarianceSolvesForTesting ( ) const
inlinenodiscardnoexcept

Definition at line 2759 of file GaussianProcessRegression.h.

2761 {
2762 return active_energy_variance_solves_for_testing_;
2763 }

◆ activeFactorOrder()

Eigen::Index gpr::GaussianProcessRegression::activeFactorOrder ( Eigen::Index full_rows) const
inlinenodiscardprotectednoexcept

Definition at line 5576 of file GaussianProcessRegression.h.

5578 {
5579 return rigid_deflation_.activeOrderFor(full_rows);
5580 }
detail::RigidDeflationState rigid_deflation_

◆ activeFitAnchorCountForTesting()

Eigen::Index gpr::GaussianProcessRegression::activeFitAnchorCountForTesting ( ) const
inlinenodiscardnoexcept

Anchors the last active correction fit conditioned its candidate objectives on (every anchor when the background has no more rows than its own fit subset).

Definition at line 628 of file GaussianProcessRegression.h.

629 {
630 return last_active_fit_anchor_count_;
631 }

◆ activeFitStartForTesting()

double gpr::GaussianProcessRegression::activeFitStartForTesting ( ) const
inlinenodiscardnoexcept

MAP objective at the start of the last active correction fit.

Definition at line 621 of file GaussianProcessRegression.h.

622 {
623 return active_fit_start_for_testing_;
624 }

◆ activeFitSupportCountForTesting()

Eigen::Index gpr::GaussianProcessRegression::activeFitSupportCountForTesting ( ) const
inlinenodiscardnoexcept

Anchors used to condition the selected correction after its support expands beyond the hyperparameter fit subset.

Definition at line 634 of file GaussianProcessRegression.h.

635 {
636 return last_active_fit_support_count_;
637 }

◆ activeKernelEvidence()

const std::vector< ActiveKernelEvidence > & gpr::GaussianProcessRegression::activeKernelEvidence ( ) const
inlinenodiscardnoexcept

Definition at line 616 of file GaussianProcessRegression.h.

617 {
618 return active_kernel_evidence_;
619 }

◆ activePosteriorObservationCount()

Eigen::Index gpr::GaussianProcessRegression::activePosteriorObservationCount ( ) const
nodiscardnoexcept

Definition at line 958 of file ActivePosterior.cpp.

960{
961 return active_posterior_ ? active_posterior_->observations.R.rows() : 0;
962}

◆ activePosteriorRefitsEnabled()

bool gpr::GaussianProcessRegression::activePosteriorRefitsEnabled ( ) const
inlinenodiscardnoexcept

Definition at line 577 of file GaussianProcessRegression.h.

578 {
579 return active_posterior_refits_;
580 }

◆ additivePairResidualsEnabled()

bool gpr::GaussianProcessRegression::additivePairResidualsEnabled ( ) const
inlinenodiscardnoexcept

Definition at line 599 of file GaussianProcessRegression.h.

600 {
601 return additive_pair_residuals_;
602 }

◆ addLayeredPriorHessianAction()

void gpr::GaussianProcessRegression::addLayeredPriorHessianAction ( const Eigen::VectorXd & position,
const Eigen::VectorXd & direction,
Eigen::VectorXd & action ) const

H_prior(x) v + H_q v, with either term absent when that mean is off.

Definition at line 891 of file GaussianProcessRegression.cpp.

894{
895 if (direction.size() != position.size() || !position.allFinite() ||
896 !direction.allFinite())
897 throw std::invalid_argument(
898 "secant quadratic mean requires a finite Hessian direction");
899 action = Eigen::VectorXd::Zero(position.size());
900 if (ffPriorMeanActive())
902 ff_prior_mean_->hessianPairs(position.transpose()), direction);
903 else if (zblPriorMeanActive())
905 zbl_prior_mean_->hessianPairs(position.transpose()), direction);
906 if (!secant_quadratic_prior_active_) return;
907 if (secant_reference_position_.size() != position.size())
908 throw std::logic_error(
909 "secant quadratic mean requires a matching query");
910 action += secant_hessian_ * direction;
911}
Eigen::MatrixXd applyPriorHessianPairs(const std::vector< PriorHessianPair > &pairs, const Eigen::MatrixBase< Derived > &directions)
Apply physical prior curvature without forming a dense Hessian.

◆ appendFixedHyperparameters()

bool gpr::GaussianProcessRegression::appendFixedHyperparameters ( const Observation & full_observation)
nodiscard

Append to a fitted posterior at fixed hyperparameters. The existing Cholesky factor must be appendable; otherwise this returns false without rebuilding or optimizing.

Definition at line 1101 of file Optimize.cpp.

1103{
1104 detail::requireJointTrainingObservation(
1105 full_observation,
1106 "GaussianProcessRegression::appendFixedHyperparameters");
1107 const Eigen::Index old_n = full_fit_observations_.R.rows();
1108 if (!has_been_optimized_ || !is_decomposed_succesfully || old_n <= 0 ||
1109 full_observation.R.rows() <= old_n ||
1110 full_observation.R.cols() != full_fit_observations_.R.cols() ||
1111 full_observation.G.cols() != full_fit_observations_.G.cols() ||
1112 !(full_observation.R.topRows(old_n).array() ==
1113 full_fit_observations_.R.array())
1114 .all() ||
1115 !(full_observation.E.topRows(old_n).array() ==
1116 full_fit_observations_.E.array())
1117 .all() ||
1118 !(full_observation.G.topRows(old_n).array() ==
1119 full_fit_observations_.G.array())
1120 .all() ||
1121 !trainingFactorAppendable(full_observation.R.rows())) {
1122 return false;
1123 }
1124
1125 struct RequireAppend {
1126 bool& flag;
1127 ~RequireAppend()
1128 {
1129 flag = false;
1130 }
1131 } require{require_factor_append_};
1132 const Observation previous_observation = full_fit_observations_;
1133 require_factor_append_ = true;
1134 try {
1135 updateModelWithFullData(full_observation);
1136 } catch (...) {
1137 require_factor_append_ = false;
1138 try {
1139 updateModelWithFullData(previous_observation);
1140 } catch (...) {
1141 // Preserve the original append exception for the C API boundary.
1142 }
1143 throw;
1144 }
1145 if (is_decomposed_succesfully) return true;
1146
1147 // A rejected border must leave the fitted posterior usable. The old
1148 // factor signature is still live because the append path commits L and C
1149 // only after the Schur complement factors successfully.
1150 require_factor_append_ = false;
1151 updateModelWithFullData(previous_observation);
1152 return false;
1153}
void updateModelWithFullData(const Observation &full_observation)
bool trainingFactorAppendable(Eigen::Index observations) const

◆ applyHssvdTrainingRowLatentCovarianceForTesting()

void gpr::GaussianProcessRegression::applyHssvdTrainingRowLatentCovarianceForTesting ( const EigenMatrix & positions,
EigenMatrix & covariance,
double total_sigma2 ) const
inline

Definition at line 2872 of file GaussianProcessRegression.h.

2875 {
2876 applyHssvdTrainingRowLatentCovariance(positions, covariance,
2877 total_sigma2);
2878 }

◆ applyHssvdTrainingRowLatentVarianceForTesting()

bool gpr::GaussianProcessRegression::applyHssvdTrainingRowLatentVarianceForTesting ( const EigenMatrix & positions,
Eigen::VectorXd & variance,
double total_sigma2 ) const
inlinenodiscard

Definition at line 2865 of file GaussianProcessRegression.h.

2868 {
2869 return applyHssvdTrainingRowLatentVariance(positions, variance,
2870 total_sigma2);
2871 }

◆ applyLikelihoodNoiseVarianceFloor()

bool gpr::GaussianProcessRegression::applyLikelihoodNoiseVarianceFloor ( double floor_sigma2,
const Observation & full_observation )

Raise the Gaussian likelihood noise variance to a floor.

A valid likelihood variance above the floor is preserved. Its physical mirror is synchronized through setLikelihoodNoiseVariance when needed.

Parameters
floor_sigma2Minimum likelihood variance in physical output sigma^2 units.
full_observationFull training observation used to rebuild noise-dependent model state after a change.
Returns
true when this call rebuilt the model state; false when the floor was invalid or no likelihood/mirror change required a rebuild.

Definition at line 357 of file GaussianProcessRegression.cpp.

359{
360 if (!std::isfinite(floor_sigma2) || !(floor_sigma2 > 0.0) ||
361 lik_gaussian == nullptr) {
362 return false;
363 }
364
365 const double current_training_sigma2 = lik_gaussian->getSigma2();
366 double effective_physical_sigma2 = floor_sigma2;
367 if (std::isfinite(current_training_sigma2) &&
368 current_training_sigma2 > 0.0) {
369 const double current_physical_sigma2 =
370 trainingToPhysicalNoiseVariance(current_training_sigma2);
371 if (std::isfinite(current_physical_sigma2) &&
372 current_physical_sigma2 > effective_physical_sigma2) {
373 effective_physical_sigma2 = current_physical_sigma2;
374 }
375 }
376
377 return setLikelihoodNoiseVariance(effective_physical_sigma2,
378 full_observation) ==
380}
LikelihoodNoiseVarianceUpdate setLikelihoodNoiseVariance(double physical_sigma2, const Observation *full_observation=nullptr)
Set the likelihood noise variance in physical output units.

◆ applyMeanHessianBlockHssvd()

bool gpr::GaussianProcessRegression::applyMeanHessianBlockHssvd ( const PreparedHssvdHessianVector & prepared,
const Eigen::MatrixXd & directions,
Eigen::MatrixXd & hessian_block ) const
nodiscard

Definition at line 1788 of file Decompose.cpp.

1791{
1792 ++hssvd_hessian_vector_calls_for_testing_;
1793 if (optimizer_state_->mean_hessian.hssvd_block_apply_fails) return false;
1794 return applyMeanHessianBlockHssvdImpl(prepared, directions, hessian_block);
1795}

◆ applyMeanHessianVectorHssvd()

bool gpr::GaussianProcessRegression::applyMeanHessianVectorHssvd ( const PreparedHssvdHessianVector & prepared,
const Eigen::VectorXd & direction,
Eigen::VectorXd & hessian_vector ) const
nodiscard

Definition at line 1701 of file Decompose.cpp.

1704{
1705 ++hssvd_hessian_vector_calls_for_testing_;
1706 Eigen::MatrixXd directions(direction.size(), 1);
1707 directions.col(0) = direction;
1708 Eigen::MatrixXd hessian_block;
1709 if (!applyMeanHessianBlockHssvdImpl(prepared, directions, hessian_block)) {
1710 return false;
1711 }
1712 hessian_vector = hessian_block.col(0);
1713 return hessian_vector.allFinite();
1714}

◆ applyPopulationPrior()

void gpr::GaussianProcessRegression::applyPopulationPrior ( const AtomsConfiguration & conf_info,
const Eigen::VectorXd & ls_k,
double own_s2_log )

Anchor the pair types the population has seen in the kernel's prior (log-Gaussian at the population's location and width); ~ls_k~ is the run's own scale per pair type and ~own_s2_log~ the run's own width (zero when it has none).

Definition at line 1357 of file GaussianProcessRegression.cpp.

1360{
1361 if (population_prior_.empty() || sexpat_cov_func == nullptr ||
1362 conf_info.n_pt <= 0)
1363 return;
1364 const auto entries = population_prior_.perPairtype(conf_info);
1365 const Eigen::Index count = conf_info.n_pt + 1;
1366 Eigen::VectorXd mu_log = sexpat_cov_func->hierarchicalPriorMu();
1367 if (mu_log.size() != count) {
1368 // No prior of the run's own: the population supplies the anchored
1369 // types, the others carry no term (a zero width) and the
1370 // amplitude keeps its own prior.
1371 mu_log = Eigen::VectorXd::Zero(count);
1372 const double magn = sexpat_cov_func->getMagnSigma2();
1373 mu_log(0) =
1374 std::isfinite(magn) && magn > 0.0 ? numerics::log(magn) : 0.0;
1375 for (Index_t k = 0; k < conf_info.n_pt; ++k) {
1376 const double lk = k < ls_k.size() ? ls_k(k) : 0.0;
1377 mu_log(k + 1) =
1378 std::isfinite(lk) && lk > 0.0 ? numerics::log(lk) : 0.0;
1379 }
1380 }
1381 Eigen::VectorXd s2_log_per = Eigen::VectorXd::Constant(count, own_s2_log);
1382 if (!(own_s2_log > 0.0)) s2_log_per(0) = 0.0;
1383 std::vector<char> anchored(static_cast<std::size_t>(conf_info.n_pt), 0);
1384 Index_t anchored_count = 0;
1385 for (Index_t k = 0; k < conf_info.n_pt; ++k) {
1386 const auto* entry = entries[static_cast<std::size_t>(k)];
1387 if (entry == nullptr || !(entry->log_length_sigma > 0.0)) continue;
1388 mu_log(k + 1) = entry->log_length_mu;
1389 s2_log_per(k + 1) = entry->log_length_sigma * entry->log_length_sigma;
1390 anchored[static_cast<std::size_t>(k)] = 1;
1391 ++anchored_count;
1392 }
1393 if (anchored_count == 0) return;
1394 sexpat_cov_func->setHierarchicalPrior(mu_log, own_s2_log, s2_log_per);
1395 sexpat_cov_func->setHierarchicalAnchorMask(std::move(anchored));
1396 if (!population_prior_reported_ && report_level >= 1) {
1397 log_man << "Population prior: " << anchored_count << " of "
1398 << conf_info.n_pt
1399 << " pair types anchored at the campaign's length scales.\n";
1400 population_prior_reported_ = true;
1401 }
1402}
double log(double x) noexcept

◆ assembleCompositeJointCovariance()

bool gpr::GaussianProcessRegression::assembleCompositeJointCovariance ( const EigenMatrix & x,
const Eigen::VectorXd & indices,
SexpatCF & covariance,
EigenMatrix & result ) const
nodiscard

Derivative tensors dC/dtheta_j of the composite joint covariance under a manifold chart, ordered as SexpatCF::combineParameters (log magnSigma2, then log lengthScale entries; only entry (0,0) enters the chart kernel).

Definition at line 1050 of file CovarianceAssembly.cpp.

1053{
1054 const auto kernel = covariance.assembledOperator();
1055 if (!kernel) return false;
1056 JointOperand operand;
1057 if (covariance.usesManifoldChart()) {
1058 operand =
1059 extractJointPositions(x, indices, covariance.manifoldDimensions());
1060 } else if (!extractCompleteJointPositions(
1061 x, indices, covariance.geodesicHeatKernel()->dimensions(),
1062 operand)) {
1063 return false;
1064 }
1065 result = scatterJointBlock(
1066 kernel->jointEnergyGradientCovariance(operand.positions), operand,
1067 operand);
1068 if (covariance.usesManifoldChart())
1069 covariance.addManifoldGeometryRowsEvaluatedForTesting(
1070 operand.positions.rows(), 0);
1071 return true;
1072}
@ x
Definition Enums.h:28

◆ assembleCompositeJointCovarianceDerivatives()

bool gpr::GaussianProcessRegression::assembleCompositeJointCovarianceDerivatives ( const EigenMatrix & x,
const Eigen::VectorXd & indices,
SexpatCF & covariance,
std::vector< EigenMatrix > & derivatives ) const
nodiscard

Definition at line 1112 of file CovarianceAssembly.cpp.

1115{
1116 derivatives.clear();
1117 if (!covariance.usesManifoldChart()) return false;
1118 const JointOperand operand =
1119 extractJointPositions(x, indices, covariance.manifoldDimensions());
1120 const auto derivative_block =
1122 auto kernel = std::make_shared<ManifoldEnergyForceKernel>(
1123 covariance.manifoldChart(), covariance.getMagnSigma2(),
1124 covariance.getLengthScaleRef()(0, 0));
1125 kernel->setDerivative(mode);
1126 const Pullback pullback{
1127 std::shared_ptr<const ManifoldEnergyForceKernel>(kernel)};
1128 return scatterJointBlock(
1129 pullback.jointEnergyGradientCovariance(operand.positions),
1130 operand, operand);
1131 };
1132 // d/d log s^2: the joint block is linear in s^2, so the derivative is the
1133 // block itself. d/d log l: the chart kernel derivative (k a r^2 and its
1134 // energy/gradient images) evaluated by the same operator algebra.
1135 derivatives.push_back(derivative_block(
1137 derivatives.push_back(derivative_block(
1139 const Eigen::Index n_length = covariance.getLengthScaleRef().size();
1140 for (Eigen::Index k = 1; k < n_length; ++k) {
1141 derivatives.emplace_back(EigenMatrix::Zero(derivatives.front().rows(),
1142 derivatives.front().cols()));
1143 }
1144 for (auto& derivative: derivatives)
1145 applyKernelNugget(derivative, x.rows());
1146 return true;
1147}

◆ assembleCompositeJointCovarianceSecondDerivative()

bool gpr::GaussianProcessRegression::assembleCompositeJointCovarianceSecondDerivative ( const EigenMatrix & x,
const Eigen::VectorXd & indices,
SexpatCF & covariance,
const Eigen::VectorXd & direction,
EigenMatrix & second ) const
nodiscard

Second directional derivative of the charted joint covariance along a hyperparameter direction p = (p_u, p_v, ...) in the combineParameters order (log magnitude, log length scale): C_pp = p_u^2 K + 2 p_u p_v K_v + p_v^2 K_vv, since the log-magnitude derivative of every block is the block itself.

Definition at line 1149 of file CovarianceAssembly.cpp.

1154{
1155 if (!covariance.usesManifoldChart() || direction.size() < 2) return false;
1156 const JointOperand operand =
1157 extractJointPositions(x, indices, covariance.manifoldDimensions());
1158 const auto block = [&](ManifoldEnergyForceKernel::Derivative mode) {
1159 auto kernel = std::make_shared<ManifoldEnergyForceKernel>(
1160 covariance.manifoldChart(), covariance.getMagnSigma2(),
1161 covariance.getLengthScaleRef()(0, 0));
1162 kernel->setDerivative(mode);
1163 const Pullback pullback{
1164 std::shared_ptr<const ManifoldEnergyForceKernel>(kernel)};
1165 return scatterJointBlock(
1166 pullback.jointEnergyGradientCovariance(operand.positions), operand,
1167 operand);
1168 };
1169 const double pu = direction(0);
1170 const double pv = direction(1);
1171 second = pu * pu * block(ManifoldEnergyForceKernel::Derivative::Value);
1172 if (pv != 0.0) {
1173 second.noalias() +=
1174 (2.0 * pu * pv) *
1176 second.noalias() +=
1177 (pv * pv) *
1179 }
1180 applyKernelNugget(second, x.rows());
1181 return true;
1182}

◆ assembleCompositeJointCrossCovariance()

bool gpr::GaussianProcessRegression::assembleCompositeJointCrossCovariance ( const EigenMatrix & left,
const EigenMatrix & right,
const Eigen::VectorXd & left_indices,
const Eigen::VectorXd & right_indices,
SexpatCF & covariance,
EigenMatrix & result ) const
nodiscard

Definition at line 1074 of file CovarianceAssembly.cpp.

1078{
1079 if (!covariance.usesManifoldChart()) {
1080 const Eigen::Index dimensions = 3 * atoms_config.atoms_mov.type.size();
1081 JointOperand left_operand, right_operand;
1082 if (!extractCompleteJointPositions(left, left_indices, dimensions,
1083 left_operand) ||
1084 !extractCompleteJointPositions(right, right_indices, dimensions,
1085 right_operand))
1086 return false;
1087 const auto kernel = covariance.assembledOperator();
1088 const EigenMatrix joint =
1089 kernel ? kernel->jointEnergyGradientCrossCovariance(
1090 left_operand.positions, right_operand.positions)
1091 : Sexpat(covariance)
1092 .jointEnergyGradientCrossCovariance(
1093 left_operand.positions, right_operand.positions);
1094 result = scatterJointBlock(joint, left_operand, right_operand);
1095 return true;
1096 }
1097 const Eigen::Index dimensions = covariance.manifoldDimensions();
1098 const JointOperand left_operand =
1099 extractJointPositions(left, left_indices, dimensions);
1100 const JointOperand right_operand =
1101 extractJointPositions(right, right_indices, dimensions);
1102 const auto kernel = covariance.assembledOperator();
1103 result =
1104 scatterJointBlock(kernel->jointEnergyGradientCrossCovariance(
1105 left_operand.positions, right_operand.positions),
1106 left_operand, right_operand);
1107 covariance.addManifoldGeometryRowsEvaluatedForTesting(
1108 left_operand.positions.rows(), right_operand.positions.rows());
1109 return true;
1110}

◆ assembleDirectionalCovarianceDerivatives()

void gpr::GaussianProcessRegression::assembleDirectionalCovarianceDerivatives ( const EigenMatrix & x,
const Eigen::VectorXd & ind_Ddim,
const Eigen::VectorXd & uDdim,
const Eigen::VectorXd & direction,
EigenMatrix & first,
EigenMatrix & second,
bool serial_per_rank = false ) const
inline

Assemble the directional first and second derivatives of the training covariance matrix for the optimized Sexpat parameters.

Public + const so that out-of-class callers (e.g. laplace::TCovSecondOrder) can request directional kernel derivatives without needing friend access; promoted from private for that purpose.

Definition at line 2627 of file GaussianProcessRegression.inl.

2631{
2632#ifndef GPR_LINALG_SCALAPACK
2633 (void)serial_per_rank;
2634#endif
2635 FieldMatrixd x_loc_0;
2636 FieldMatrixIdx dims1, dims2;
2637 FieldMatrixd block_first, block_second;
2638 const Index_t number_of_rep_indices =
2640
2641 x_loc_0.resize(number_of_rep_indices, static_cast<Index_t>(x.cols()) + 1);
2642 x_loc_0.setZero();
2643 dims1.resize(1, 1);
2644 dims2.resize(1, 1);
2645
2646 std::vector<FieldMatrixd> x_loc_by_udim(
2647 static_cast<std::size_t>(uDdim.size()));
2648 for (Index_t n = 0; n < uDdim.size(); ++n) {
2649 auto& x_loc = x_loc_by_udim[static_cast<std::size_t>(n)];
2650 x_loc.resize(number_of_rep_indices, static_cast<Index_t>(x.cols()) + 1);
2651 x_loc.setZero();
2652 extractCoordinatesByIndex(x, ind_Ddim, uDdim[n], x_loc);
2653 }
2654
2655 first.resize(x.rows(), x.rows());
2656 first.setZero();
2657 second.resize(x.rows(), x.rows());
2658 second.setZero();
2659
2660#ifdef GPR_LINALG_SCALAPACK
2661 int _mpi_rank = 0, _mpi_np = 1;
2662 if (!serial_per_rank) {
2663 auto& _mpi_st = backend().distributed();
2664 _mpi_rank = _mpi_st.myrank();
2665 _mpi_np = _mpi_st.nprocs();
2666 }
2667#else
2668 const int _mpi_rank = 0, _mpi_np = 1;
2669#endif
2670 int _mpi_blk = 0;
2671
2672 extractCoordinatesByIndex(x, ind_Ddim, 0, x_loc_0);
2673 if (ownsBlock(_mpi_blk++, _mpi_rank, _mpi_np, serial_per_rank)) {
2674 sexpat_cov_func->calculateDirectionalCovarianceMatrix(
2675 x_loc_0, x_loc_0, direction, block_first, block_second);
2676 if (block_first.size() != 0) {
2677 assignBlockToMatrix(ind_Ddim, ind_Ddim, 0, 0, block_first, first);
2678 assignBlockToMatrix(ind_Ddim, ind_Ddim, 0, 0, block_second, second);
2679 }
2680 }
2681
2682 for (Index_t n = 0; n < uDdim.size(); ++n) {
2683 dims1(0, 0) = uDdim[n];
2684 auto& x_loc_1 = x_loc_by_udim[static_cast<std::size_t>(n)];
2685
2686 if (ownsBlock(_mpi_blk++, _mpi_rank, _mpi_np, serial_per_rank)) {
2688 ->calculateDirectionalCovarianceMatrixWithDerivatives(
2689 x_loc_1, x_loc_0, dims1, direction, block_first,
2690 block_second);
2691 if (block_first.size() != 0) {
2692 assignBlockToMatrix(ind_Ddim, ind_Ddim, uDdim[n], 0,
2693 block_first, first);
2694 assignBlockToMatrix(ind_Ddim, ind_Ddim, 0, uDdim[n],
2695 block_first, first, true);
2696 assignBlockToMatrix(ind_Ddim, ind_Ddim, uDdim[n], 0,
2697 block_second, second);
2698 assignBlockToMatrix(ind_Ddim, ind_Ddim, 0, uDdim[n],
2699 block_second, second, true);
2700 }
2701
2703 ->calculateDirectionalCovarianceMatrixWithDerivatives2(
2704 x_loc_1, x_loc_1, dims1, dims1, direction, block_first,
2705 block_second);
2706 if (block_first.size() != 0) {
2707 assignBlockToMatrix(ind_Ddim, ind_Ddim, uDdim[n], uDdim[n],
2708 block_first, first);
2709 assignBlockToMatrix(ind_Ddim, ind_Ddim, uDdim[n], uDdim[n],
2710 block_second, second);
2711 }
2712 }
2713
2714 for (Index_t m = n + 1; m < uDdim.size(); ++m) {
2715 if (ownsBlock(_mpi_blk++, _mpi_rank, _mpi_np, serial_per_rank)) {
2716 dims2(0, 0) = uDdim[m];
2717 auto& x_loc_2 = x_loc_by_udim[static_cast<std::size_t>(m)];
2719 ->calculateDirectionalCovarianceMatrixWithDerivatives2(
2720 x_loc_1, x_loc_2, dims1, dims2, direction, block_first,
2721 block_second);
2722 if (block_first.size() != 0) {
2723 assignBlockToMatrix(ind_Ddim, ind_Ddim, uDdim[n], uDdim[m],
2724 block_first, first);
2725 assignBlockToMatrix(ind_Ddim, ind_Ddim, uDdim[m], uDdim[n],
2726 block_first, first, true);
2727 assignBlockToMatrix(ind_Ddim, ind_Ddim, uDdim[n], uDdim[m],
2728 block_second, second);
2729 assignBlockToMatrix(ind_Ddim, ind_Ddim, uDdim[m], uDdim[n],
2730 block_second, second, true);
2731 }
2732 }
2733 }
2734 }
2735
2736#ifdef GPR_LINALG_SCALAPACK
2737 if (!serial_per_rank && _mpi_np > 1) {
2738 backend().ordered_sum_bcast(first.data(),
2739 static_cast<int>(first.size()));
2740 backend().ordered_sum_bcast(second.data(),
2741 static_cast<int>(second.size()));
2742 }
2743#endif
2744
2745 applyKernelNugget(first, x.rows());
2746 applyKernelNugget(second, x.rows());
2747
2748 const Eigen::Index n_cov_params = covarianceParameterCount();
2749 if (direction.size() > n_cov_params) {
2750 const double noise = likelihoodNoiseVariance();
2751 if (noise > 0.0) {
2752 const double noise_dir = direction(direction.size() - 1);
2753 first.diagonal().array() += noise * noise_dir;
2754 second.diagonal().array() += noise * noise_dir * noise_dir;
2755 }
2756 }
2757}
void assignBlockToMatrix(const Eigen::VectorXd &ind_Ddim1, const Eigen::VectorXd &ind_Ddim2, const Index_t row_val, const Index_t col_val, const FieldMatrixd &field, EigenMatrix &matrix, bool transpose_field=false) const
Assign field to matrix according to indices form ind_Ddim1 and ind_Ddim2.
Index_t getNumberOfRepetitiveIndices(const Eigen::VectorXd &ind_Ddim) const
Count number of the first repetitive indices in ind_Ddim .
bool ownsBlock(long block_idx, int rank, int nprocs, bool serial_per_rank)

◆ assembleDirectionalCovarianceDerivativesFromGeometry()

bool gpr::GaussianProcessRegression::assembleDirectionalCovarianceDerivativesFromGeometry ( const TrainingKernelGeometry & geom,
const EigenMatrix & x,
const Eigen::VectorXd & ind_Ddim,
const Eigen::VectorXd & uDdim,
const Eigen::VectorXd & direction,
EigenMatrix & first,
EigenMatrix & second,
bool serial_per_rank = false ) const
inlinenodiscard

Definition at line 2760 of file GaussianProcessRegression.inl.

2765{
2766#ifndef GPR_LINALG_SCALAPACK
2767 (void)serial_per_rank;
2768#endif
2769 first.resize(0, 0);
2770 second.resize(0, 0);
2771#ifdef GPR_LINALG_SCALAPACK
2772 int mpi_rank = 0, mpi_np = 1;
2773 if (!serial_per_rank) {
2774 auto& mpi_st = backend().distributed();
2775 mpi_st.initialize();
2776 mpi_rank = mpi_st.myrank();
2777 mpi_np = mpi_st.nprocs();
2778 }
2779#else
2780 const int mpi_rank = 0, mpi_np = 1;
2781#endif
2782
2783 [[maybe_unused]] bool pair_tiles_used = false;
2784 const bool local_ok = [&]() {
2785 if (!geom.valid || sexpat_cov_func == nullptr) return false;
2786 if (geom.n != x.rows() || ind_Ddim.size() != x.rows()) return false;
2787 if (uDdim.size() != geom.uDdim.size()) return false;
2788 for (Eigen::Index i = 0; i < uDdim.size(); ++i) {
2789 if (static_cast<Index_t>(uDdim(i)) !=
2790 static_cast<Index_t>(geom.uDdim(i))) {
2791 return false;
2792 }
2793 }
2794
2795 const auto local = tryPairLocalDirectionalCovariance(
2796 geom, ind_Ddim, direction, first, second, mpi_rank, mpi_np);
2797 if (local.has_value()) {
2798 pair_tiles_used = true;
2799 return *local;
2800 }
2801
2802 const Eigen::VectorXd theta = sexpat_cov_func->combineParameters();
2803 FieldMatrixd shared_kernel;
2804 if (!sexpat_cov_func->buildSharedKernel(geom.shared_distance_neg_per_pt,
2805 theta, shared_kernel)) {
2806 return false;
2807 }
2808
2809 first.resize(x.rows(), x.rows());
2810 first.setZero();
2811 second.resize(x.rows(), x.rows());
2812 second.setZero();
2813
2814 std::vector<std::size_t> owned;
2815 owned.reserve(geom.blocks.size());
2816 for (std::size_t index = 0; index < geom.blocks.size(); ++index) {
2817 if (ownsBlock(static_cast<long>(index), mpi_rank, mpi_np,
2818 serial_per_rank))
2819 owned.push_back(index);
2820 }
2821 std::vector<uint8_t> block_ok(owned.size(), 1);
2822 std::atomic<std::size_t> resolved{0};
2823 const std::size_t workers = std::max<std::size_t>(
2824 1, std::min(owned.size(), static_cast<std::size_t>(
2825 backend().local().concurrency())));
2826 if (!owned.empty()) {
2827 backend().local().forEach(workers, [&](std::size_t worker) {
2828 FieldMatrixd block_first, block_second, block_kernel;
2829 SexpatCF::CrossBlockGeometry streamed_scratch;
2830 for (std::size_t task = worker; task < owned.size();
2831 task += workers) {
2832 const auto& block = geom.blocks[owned[task]];
2833 const SexpatCF::CrossBlockGeometry* block_geometry =
2835 block, streamed_scratch);
2836 if (block_geometry == nullptr) {
2837 block_ok[task] = 0;
2838 return;
2839 }
2840 resolved.fetch_add(1, std::memory_order_relaxed);
2841 const FieldMatrixd* kernel = &shared_kernel;
2842 const std::vector<FieldMatrixd>* distances =
2843 &geom.shared_distance_neg_per_pt;
2844 if (!geom.shared_coordinates &&
2845 block.derivative_options != 0) {
2846 distances = &block_geometry->distance;
2847 if (!sexpat_cov_func->buildSharedKernel(
2848 *distances, theta, block_kernel)) {
2849 block_ok[task] = 0;
2850 return;
2851 }
2852 kernel = &block_kernel;
2853 }
2854
2855 bool ok = false;
2856 if (block.derivative_options == 0) {
2857 ok =
2859 ->calculateDirectionalCovarianceMatrixFromGeometry(
2860 *kernel, *distances, theta, direction,
2861 block_first, block_second);
2862 } else if (block.derivative_options ==
2864 ok =
2866 ->calculateDirectionalCovarianceMatrixWithDerivativesFromGeometry(
2867 *block_geometry, *kernel, *distances, theta,
2868 direction, block_first, block_second);
2869 } else {
2870 ok =
2872 ->calculateDirectionalCovarianceMatrixWithDerivatives2FromGeometry(
2873 *block_geometry, *kernel, *distances, theta,
2874 direction, block_first, block_second);
2875 }
2876 if (!ok || block_first.size() == 0 ||
2877 block_second.size() == 0) {
2878 block_ok[task] = 0;
2879 return;
2880 }
2881
2882 if (block.block_n == 0 && block.block_m == 0 &&
2883 block.derivative_options == 0) {
2884 if (block_first.rows() > first.rows() ||
2885 block_first.cols() > first.cols() ||
2886 block_second.rows() > second.rows() ||
2887 block_second.cols() > second.cols()) {
2888 block_ok[task] = 0;
2889 return;
2890 }
2891 first.block(0, 0, block_first.rows(),
2892 block_first.cols()) = block_first;
2893 second.block(0, 0, block_second.rows(),
2894 block_second.cols()) = block_second;
2895 } else if (block.block_n != 0 && block.block_m == 0) {
2896 assignBlockToMatrix(ind_Ddim, ind_Ddim, block.block_n,
2897 0, block_first, first);
2898 assignBlockToMatrix(ind_Ddim, ind_Ddim, 0,
2899 block.block_n, block_first, first,
2900 /*transpose_field=*/true);
2901 assignBlockToMatrix(ind_Ddim, ind_Ddim, block.block_n,
2902 0, block_second, second);
2903 assignBlockToMatrix(ind_Ddim, ind_Ddim, 0,
2904 block.block_n, block_second, second,
2905 /*transpose_field=*/true);
2906 } else if (block.block_n == block.block_m) {
2907 assignBlockToMatrix(ind_Ddim, ind_Ddim, block.block_n,
2908 block.block_n, block_first, first);
2909 assignBlockToMatrix(ind_Ddim, ind_Ddim, block.block_n,
2910 block.block_n, block_second,
2911 second);
2912 } else {
2913 assignBlockToMatrix(ind_Ddim, ind_Ddim, block.block_n,
2914 block.block_m, block_first, first);
2915 assignBlockToMatrix(ind_Ddim, ind_Ddim, block.block_m,
2916 block.block_n, block_first, first,
2917 /*transpose_field=*/true);
2918 assignBlockToMatrix(ind_Ddim, ind_Ddim, block.block_n,
2919 block.block_m, block_second,
2920 second);
2921 assignBlockToMatrix(ind_Ddim, ind_Ddim, block.block_m,
2922 block.block_n, block_second, second,
2923 /*transpose_field=*/true);
2924 }
2925 }
2926 });
2927 }
2928 geom.directional_geometry_blocks_for_testing += resolved.load();
2929 if (std::find(block_ok.begin(), block_ok.end(), 0) != block_ok.end())
2930 return false;
2931
2932 return true;
2933 }();
2934 bool failed = !local_ok;
2935#ifdef GPR_LINALG_SCALAPACK
2936 if (!serial_per_rank && mpi_np > 1) {
2937 int state[3] = {failed, pair_tiles_used, !pair_tiles_used};
2938 MPI_Allreduce(MPI_IN_PLACE, state, 3, MPI_INT, MPI_MAX,
2939 backend().distributed().world_comm());
2940 failed = state[0] || (state[1] && state[2]);
2941 }
2942#endif
2943 // All ranks agree on rejection before entering covariance collectives.
2944 if (failed) {
2945 first.resize(0, 0);
2946 second.resize(0, 0);
2947 return false;
2948 }
2949
2950#ifdef GPR_LINALG_SCALAPACK
2951 if (!serial_per_rank && mpi_np > 1) {
2952 if (pair_tiles_used) {
2953 linalg::replicate_owned_values(first.data(), first.size(),
2954 backend().mpi());
2955 linalg::replicate_owned_values(second.data(), second.size(),
2956 backend().mpi());
2957 } else {
2958 backend().ordered_sum_bcast(first.data(),
2959 static_cast<int>(first.size()));
2960 backend().ordered_sum_bcast(second.data(),
2961 static_cast<int>(second.size()));
2962 }
2963 }
2964#endif
2965
2966 applyKernelNugget(first, x.rows());
2967 applyKernelNugget(second, x.rows());
2968
2969 const Eigen::Index n_cov_params = covarianceParameterCount();
2970 if (direction.size() > n_cov_params) {
2971 const double noise = likelihoodNoiseVariance();
2972 if (noise > 0.0) {
2973 const double noise_dir = direction(direction.size() - 1);
2974 first.diagonal().array() += noise * noise_dir;
2975 second.diagonal().array() += noise * noise_dir * noise_dir;
2976 }
2977 }
2978 return true;
2979}
@ D1
Definition Enums.h:19
std::optional< bool > tryPairLocalDirectionalCovariance(const TrainingKernelGeometry &geom, const Eigen::VectorXd &indices, const Eigen::VectorXd &direction, EigenMatrix &first, EigenMatrix &second, int rank=0, int ranks=1) const
const LocalExecutor & local() const noexcept
void forEach(std::size_t count, Operation &&operation, Grain grain=Grain::Fine) const
void replicate_owned_values(double *data, std::size_t count, const MpiContext &context)
const SexpatCF::CrossBlockGeometry * resolveTrainingBlockGeometry(const SexpatCF &covariance, const TrainingKernelGeometry &geom, const TrainingKernelGeometryBlock &block, SexpatCF::CrossBlockGeometry &scratch)
bool resolved(Dual value, Dual error, const BridgeResidualOptions &options)

◆ assembleExactHessian()

bool gpr::GaussianProcessRegression::assembleExactHessian ( const Eigen::VectorXd & x_ind,
const EigenMatrix & x,
const Eigen::VectorXd & y,
int n_hyperparameters,
Eigen::MatrixXd & H )

Assemble the full p x p observed-information Hessian of the negative log marginal likelihood at the current hyperparameters.

Uses the evaluateDirectionalCurvature oracle plus the polarisation identity validated symbolically in python/tests/test_sympy_laplace.py::test_polarisation_identity_recovers_off_diagonal:

H(i,i) = e_i^T H e_i (p direct calls) H(i,j) = ( (e_i+e_j)^T H (e_i+e_j)

  • e_i^T H e_i
  • e_j^T H e_j ) / 2 (p(p-1)/2 extra calls)

Total: p(p+1)/2 directional oracle calls, each of which reuses the cached Cholesky factor L and alpha. Symmetrised on the way out.

Parameters
x_indunique-index vector (same semantics as evaluateDirectionalCurvature).
xtraining input matrix.
ytraining targets.
n_hyperparametersp – length of the hyperparameter vector the directional oracle is parameterised by (the direction argument to evaluateDirectionalCurvature has this length).
H[out] p x p observed Hessian. Resized to (p, p) on successful return.
Returns
true if the oracle returned a finite curvature at every probe direction. false on any failure; H is left NaN.

Definition at line 568 of file Hessian.cpp.

571{
572 if (n_hyperparameters <= 0) {
573 H.resize(0, 0);
574 return false;
575 }
577 x_ind, x, y,
578 Eigen::MatrixXd::Identity(n_hyperparameters, n_hyperparameters), H);
579}
@ y
Definition Enums.h:28
bool assembleHessianInDirections(const Eigen::VectorXd &x_ind, const EigenMatrix &x, const Eigen::VectorXd &y, const Eigen::MatrixXd &directions, Eigen::MatrixXd &H)
Definition Hessian.cpp:581

◆ assembleExactHessianLocalDense()

bool gpr::GaussianProcessRegression::assembleExactHessianLocalDense ( const Eigen::VectorXd & x_ind,
const EigenMatrix & x,
const Eigen::VectorXd & y,
int n_hyperparameters,
Eigen::MatrixXd & H )

Definition at line 945 of file Hessian.cpp.

948{
949 const int p = n_hyperparameters;
950 H = Eigen::MatrixXd::Constant(p, p,
951 std::numeric_limits<double>::quiet_NaN());
952 if (p <= 0 || sexpat_cov_func == nullptr || y.rows() != x.rows()) {
953 return false;
954 }
956 hyperparameter_objective_mode_ == HyperparameterObjectiveMode::LOO ||
957 hyperparameter_objective_mode_ ==
959 return false;
960 }
961 // The local oracle uses the same pair-distance derivative assembly.
962 if (sexpat_cov_func->usesManifoldChart()) return false;
963
964 EigenMatrix C_local;
965 evaluateTrainingCovarianceMatrix(x, x_ind, C_local,
966 /*serial_per_rank=*/true,
967 /*include_constant=*/false);
968 if (jitter_sigma2 > 0.0) C_local.diagonal().array() += jitter_sigma2;
969
970 Eigen::LLT<EigenMatrix> llt(C_local);
971 if (llt.info() != Eigen::Success) return false;
972 EigenMatrix factor = llt.matrixL();
973 if (!linalg::rank_one_update_lower(factor, detail::constantCovarianceUpdate(
974 const_cov_fun.get(), x_ind)))
975 return false;
976 const auto solve = [&](const EigenMatrix& rhs) -> EigenMatrix {
977 const EigenMatrix forward =
978 factor.triangularView<Eigen::Lower>().solve(rhs);
979 return factor.transpose().triangularView<Eigen::Upper>().solve(forward);
980 };
981
982 const Eigen::VectorXd alpha = solve(y);
983 const EigenMatrix invC =
984 solve(EigenMatrix::Identity(C_local.rows(), C_local.cols()));
985
986 Eigen::VectorXd uDdim;
987 extractUniqueIndices(x_ind, uDdim);
988 TrainingKernelGeometry training_geometry;
989 const bool geometry_ready =
990 prepareTrainingKernelGeometry(x, x_ind, training_geometry);
991
992 auto probe = [&](const Eigen::VectorXd& direction) -> double {
993 EigenMatrix first, second;
994 if (!geometry_ready ||
996 training_geometry, x, x_ind, uDdim, direction, first, second,
997 /*serial_per_rank=*/true)) {
998 assembleDirectionalCovarianceDerivatives(x, x_ind, uDdim, direction,
999 first, second,
1000 /*serial_per_rank=*/true);
1001 }
1002 if (first.size() == 0 || second.size() == 0) {
1003 return std::numeric_limits<double>::quiet_NaN();
1004 }
1005
1006 const double prior_curvature =
1007 -sexpat_cov_func->calculateDirectionalLogPriorCurvature(direction);
1008 const EigenMatrix solve_first = solve(first);
1009 const double trace_adad =
1010 localTraceProduct(solve_first, solve_first.transpose());
1011 const double trace_ae = localTraceProduct(invC, second);
1012 const Eigen::VectorXd v = first * alpha;
1013 const Eigen::VectorXd z = solve(v);
1014 const double quad = v.dot(z);
1015 const double alpha_e_alpha = alpha.dot(second * alpha);
1016 const double curvature =
1017 0.5 * (-trace_adad + trace_ae + 2.0 * quad - alpha_e_alpha) +
1018 prior_curvature;
1019 return std::isfinite(curvature)
1020 ? curvature
1021 : std::numeric_limits<double>::quiet_NaN();
1022 };
1023
1024 const int n_diag = p;
1025 const int n_off = p * (p - 1) / 2;
1026 const int n_probes = n_diag + n_off;
1027
1028 auto direction_for_probe = [p, n_diag](int probe_idx) {
1029 Eigen::VectorXd direction = Eigen::VectorXd::Zero(p);
1030 if (probe_idx < n_diag) {
1031 direction(probe_idx) = 1.0;
1032 return direction;
1033 }
1034
1035 int off_idx = probe_idx - n_diag;
1036 for (int i = 0; i < p; ++i) {
1037 const int row_count = p - i - 1;
1038 if (off_idx < row_count) {
1039 const int j = i + 1 + off_idx;
1040 direction(i) = 1.0;
1041 direction(j) = 1.0;
1042 return direction;
1043 }
1044 off_idx -= row_count;
1045 }
1046 return direction;
1047 };
1048
1049 const std::function<double(int)> probe_by_index = [&](int probe_idx) {
1050 return probe(direction_for_probe(probe_idx));
1051 };
1052
1053 const linalg::ProbeExecutor probe_exec;
1054 const Eigen::VectorXd probe_values = probe_exec.run(
1055 n_probes, probe_by_index, linalg::KernelInverse::Kind::RankLocal,
1057 if (probe_values.size() != n_probes || !probe_values.allFinite()) {
1058 return false;
1059 }
1060
1061 for (int i = 0; i < p; ++i)
1062 H(i, i) = probe_values(i);
1063 int off_idx = 0;
1064 for (int i = 0; i < p; ++i) {
1065 for (int j = i + 1; j < p; ++j, ++off_idx) {
1066 const double h_sum = probe_values(n_diag + off_idx);
1067 const double h_ij = 0.5 * (h_sum - H(i, i) - H(j, j));
1068 H(i, j) = h_ij;
1069 H(j, i) = h_ij;
1070 }
1071 }
1072
1073 return true;
1074}
@ z
Definition Enums.h:28
bool prepareTrainingKernelGeometry(const EigenMatrix &x, const Eigen::VectorXd &x_ind, TrainingKernelGeometry &out, bool reused=false) const
bool assembleDirectionalCovarianceDerivativesFromGeometry(const TrainingKernelGeometry &geom, const EigenMatrix &x, const Eigen::VectorXd &ind_Ddim, const Eigen::VectorXd &uDdim, const Eigen::VectorXd &direction, EigenMatrix &first, EigenMatrix &second, bool serial_per_rank=false) const
void extractUniqueIndices(const Eigen::VectorXd &input_ind, Eigen::VectorXd &output_ind) const
Extract unique indices from the input vector.
void assembleDirectionalCovarianceDerivatives(const EigenMatrix &x, const Eigen::VectorXd &ind_Ddim, const Eigen::VectorXd &uDdim, const Eigen::VectorXd &direction, EigenMatrix &first, EigenMatrix &second, bool serial_per_rank=false) const
Assemble the directional first and second derivatives of the training covariance matrix for the optim...
void evaluateTrainingCovarianceMatrix(const EigenMatrix &x, const Eigen::VectorXd &x_ind, EigenMatrix &cov_matrix, bool serial_per_rank=false, bool include_constant=true, bool include_noise=true)
Evaluate training covariance matrix (gp_cov + noise covariance).
bool rank_one_update_lower(EigenMatrix &lower, const Eigen::VectorXd &vector)
static MpiContext local() noexcept
Definition MpiContext.h:75

◆ assembleHessianInDirections()

bool gpr::GaussianProcessRegression::assembleHessianInDirections ( const Eigen::VectorXd & x_ind,
const EigenMatrix & x,
const Eigen::VectorXd & y,
const Eigen::MatrixXd & directions,
Eigen::MatrixXd & H )

Assemble J^T H J directly from the columns of J, without probing directions excluded by the parameter constraints.

Definition at line 581 of file Hessian.cpp.

585{
586 // Polarisation identity, symbolically validated in
587 // python/tests/test_sympy_laplace.py::test_polarisation_identity_recovers_off_diagonal.
588 // Uses p(p+1)/2 directional probes at theta*: p for the diagonal,
589 // p(p-1)/2 for the off-diagonal recovered via
590 // H_ij = ( (e_i+e_j)^T H (e_i+e_j) - H_ii - H_jj ) / 2.
591 //
592 // alpha = K^{-1} y and invC = K^{-1} are
593 // loop-invariants of the Cholesky polarisation path: they depend on
594 // the training-set factor, not on the probe direction. Structured
595 // HS-SVD objectives instead reuse evaluateDirectionalCurvature so the
596 // same Hessian probes are contracted through the orthonormal Psi basis.
597 const int p = static_cast<int>(directions.cols());
598 H = Eigen::MatrixXd::Constant(p, p,
599 std::numeric_limits<double>::quiet_NaN());
600 if (p <= 0 || directions.rows() < p || !directions.allFinite())
601 return false;
603 hyperparameter_objective_mode_ == HyperparameterObjectiveMode::LOO ||
604 hyperparameter_objective_mode_ ==
606 return false;
607 }
608 if (sexpat_cov_func == nullptr) return false;
609 // Pair-distance second derivatives do not describe a charted kernel.
610 if (sexpat_cov_func->usesManifoldChart()) return false;
611 if (!is_decomposed_succesfully) return false;
612 auto hssvd_curvature_ready = [&]() {
613 return use_hssvd_backend_ && use_hssvd_objective_contractions_ &&
614 hssvdObjectiveStampMatches() &&
615 // The Cholesky-trace SCG objective state caches a factor and an
616 // alpha tied to the last line-search theta; rebuild a clean
617 // self-contained Q-form objective for the exact-Hessian probes
618 // at theta* rather than reuse it.
619 !hssvd_objective_trace_via_cholesky_ &&
620 hssvd_objective_alpha_.size() == y.size() &&
621 hssvd_objective_trace_basis_.rows() == y.size() &&
622 hssvd_objective_trace_weighted_basis_.rows() == y.size() &&
623 hssvd_objective_trace_basis_.cols() ==
624 hssvd_objective_trace_weighted_basis_.cols();
625 };
626 bool use_hssvd_curvature = hssvd_curvature_ready();
627 if (!use_hssvd_curvature && use_hssvd_backend_ &&
628 use_hssvd_objective_contractions_) {
629 const double total_sigma2 =
630 (lik_gaussian ? lik_gaussian->getSigma2() : 0.0) + jitter_sigma2;
631 auto install_noisy_hssvd_objective =
632 [&](const StableBasisND& basis, const Eigen::VectorXd& y_factor,
633 const bool unpermute_from_factor_layout) {
634 if (basis.rank() <= 0 || basis.numObs() != y.size() ||
635 y_factor.size() != y.size() || !(total_sigma2 > 0.0)) {
636 return false;
637 }
638 const StableBasisPosteriorWeights weights =
639 basis.noisyPosteriorWeights(y_factor, total_sigma2);
640 const EigenMatrix& Q = basis.leftSingularVectors();
641 const Eigen::ArrayXd s2 =
642 basis.singularValues().array().square();
643 const Eigen::VectorXd shrink =
644 (s2 / (s2 + total_sigma2)).matrix();
645 const EigenMatrix Qshrink = Q * shrink.asDiagonal();
646 clearHssvdPendingCovariance();
647 hssvd_objective_trace_basis_ =
648 unpermute_from_factor_layout
650 : Q;
651 hssvd_objective_trace_weighted_basis_ =
652 unpermute_from_factor_layout
653 ? gpr::unpermuteMatrixRows(Qshrink,
655 : Qshrink;
656 hssvd_objective_alpha_ =
657 unpermute_from_factor_layout
658 ? gpr::unpermuteVector(weights.alpha,
660 : weights.alpha;
661 hssvd_objective_trace_inv_noise_ = 1.0 / total_sigma2;
662 hssvd_objective_trace_direct_inverse_ = false;
663 // This install builds the orthonormal Q-form trace state with
664 // no cached Cholesky factor, so the curvature must use the
665 // Q-form, not the Cholesky path. Clear any stale via-cholesky
666 // flag left by a prior geometry objective evaluation.
667 hssvd_objective_trace_via_cholesky_ = false;
668 hssvd_objective_basis_valid_ =
669 hssvd_objective_alpha_.size() == y.size() &&
670 hssvd_objective_alpha_.allFinite();
671 stampHssvdObjective();
672 return hssvd_curvature_ready();
673 };
674
675 // The HS-SVD basis the posterior is fitted with is the curvature
676 // model consistent with that posterior, and it is rank-sized (n x
677 // r). It is tried first. The full-spectrum rebuild below is the
678 // fallback when no valid basis exists: it materialises the dense
679 // noisy kernel, its symmetrised copy and a complete eigenvector
680 // matrix (n x n each), which on a 16-image, 14-atom band with 200
681 // rows (8600 joint rows) took the process to 17 GB and the OOM
682 // killer (17_claisen), for a curvature the truncated model does not
683 // even use.
684 if (!use_hssvd_curvature && hssvd_basis_valid_ &&
685 hssvd_basis_.rank() > 0 && hssvd_basis_.numObs() == y.size() &&
686 total_sigma2 > 0.0) {
687 use_hssvd_curvature =
688 install_noisy_hssvd_objective(hssvd_basis_, y,
689 /*unpermute_from_factor_layout=*/
690 false);
691 }
692 // Rebuild a self-contained Q-form objective at theta* from the noisy
693 // kernel C (full spectrum mu_i = eig(C)). This leaves no Cholesky-trace
694 // flag or cached factor, so the Laplace mean path that follows is not
695 // perturbed, and the curvature is consistent at theta*.
696 if (!use_hssvd_curvature && total_sigma2 > 0.0) {
697 TrainingKernelGeometry geom;
698 if (prepareTrainingKernelGeometry(x, x_ind, geom)) {
700 EigenMatrix noisy_cov;
702 geom, x, x_ind, noisy_cov,
703 /*serial_per_rank=*/false)) {
704 const bool permuted_factor_layout =
706 static_cast<Eigen::Index>(
707 training_permutation_.perm.size()) == y.size();
708 if (permuted_factor_layout) {
709 noisy_cov = gpr::permuteSymmetricMatrix(
710 noisy_cov, training_permutation_);
711 }
712 if (jitter_sigma2 > 0.0) {
713 noisy_cov.diagonal().array() += jitter_sigma2;
714 }
715 if (use_correction_) {
716 const double K_sum = noisy_cov.diagonal().sum();
717 const Eigen::Index n_ind = noisy_cov.rows();
718 const double denom = 1.0 / correction_eps_ -
719 static_cast<double>(n_ind * n_ind);
720 if (std::abs(denom) > 1e-30) {
721 const double corr = K_sum * K_sum / denom;
722 noisy_cov.diagonal().array() += corr;
723 }
724 }
725
726 noisy_cov =
727 (0.5 * (noisy_cov + noisy_cov.transpose())).eval();
728
729 // Factorize the noisy kernel directly (full spectrum
730 // mu_i = eig(C)); the signal-kernel subtract-then-
731 // eigendecompose path loses precision on an
732 // ill-conditioned C and can flip the Hessian sign.
733 StableBasisND objective_basis(backend_context_);
734 objective_basis.factorizeNoisyKernel(noisy_cov,
735 total_sigma2);
736 const Eigen::VectorXd y_factor =
737 permuted_factor_layout ? permuteTrainingVector(y) : y;
738 use_hssvd_curvature = install_noisy_hssvd_objective(
739 objective_basis, y_factor, permuted_factor_layout);
740 }
741 }
742 }
743 if (!use_hssvd_curvature) return false;
744 }
745
746#ifdef GPR_LINALG_SCALAPACK
747 const int mpi_nprocs = backend().distributed().nprocs();
748 const bool distributed_probes = mpi_nprocs > 1;
749#else
750 constexpr bool distributed_probes = false;
751#endif
752
753 Eigen::VectorXd alpha;
754 EigenMatrix invC;
755 // The deflated objective is contracted as in evaluateDirectionalCurvature.
756 bool deflated = false;
757 if (!use_hssvd_curvature) {
758 const bool factor_ready = hasTrainingCholeskyFactor(y.rows());
759 if (b.rows() != activeFactorOrder(y.rows()) || !factor_ready) {
760 // Every polarization probe uses the same owned training factor.
761 if (!factor_ready && x.rows() > 0) {
762 (void)decomposeCovarianceMatrix(x, x_ind);
763 if (!is_decomposed_succesfully) return false;
764 }
766 }
767 // A device-resident posterior leaves b empty and keeps the weights on
768 // the device.
769#ifdef GPR_LINALG_KOKKOS
770 if (hasDevicePosterior()) {
772 alpha = a;
773 } else
774#endif
775 alpha = trainingSolver().unwhiten(b);
776 deflated = rigid_deflation_.isActiveForFullOrder(y.rows());
777 if (deflated && rigid_deflation_.a_rigid.size() != y.rows()) {
778 rigid_deflation_.updateTargetStats(
780 }
781 // The trace tr(C^-1 C_dd) is linear in the second derivative.
782 // One inverse of the common training factor serves every direction;
783 // solving against each C_dd repeats cubic work for the same operator.
784 invC = trainingSolver().inverse();
785 const Eigen::Index order = activeFactorOrder(y.rows());
786 if (alpha.size() != order || invC.rows() != order ||
787 invC.cols() != order || !invC.allFinite())
788 return false;
789 }
790 Eigen::VectorXd uDdim;
791 if (!use_hssvd_curvature) extractUniqueIndices(x_ind, uDdim);
792 TrainingKernelGeometry training_geometry;
793 const bool geometry_ready =
794 prepareTrainingKernelGeometry(x, x_ind, training_geometry);
795
796 auto probe = [&](const Eigen::VectorXd& direction) -> double {
797 PhaseTimers::notePeak("curvature_probe");
798 if (use_hssvd_curvature) {
799 double curvature = std::numeric_limits<double>::quiet_NaN();
801 x_ind, x, y, direction, curvature,
802 geometry_ready ? &training_geometry : nullptr)
803 ? curvature
804 : std::numeric_limits<double>::quiet_NaN();
805 }
806
807 EigenMatrix first, second;
808 if (!geometry_ready ||
810 training_geometry, x, x_ind, uDdim, direction, first, second,
811 /*serial_per_rank=*/false)) {
812 assembleDirectionalCovarianceDerivatives(x, x_ind, uDdim, direction,
813 first, second,
814 /*serial_per_rank=*/false);
815 }
816 if (first.size() == 0 || second.size() == 0) {
817 return std::numeric_limits<double>::quiet_NaN();
818 }
822 }
823 double rigid_curvature = 0.0;
824 if (deflated) {
825 first = rigid_deflation_.projectSymmetric(first);
826 second = rigid_deflation_.projectSymmetric(second);
827 const auto [noise_first, noise_second] =
828 rigidNoiseDerivatives(direction);
829 rigid_curvature = rigid_deflation_.rigidCurvature(
830 noise_first, noise_first, noise_second);
831 }
832
833 const double prior_curvature =
834 -sexpat_cov_func->calculateDirectionalLogPriorCurvature(direction);
835
836 const EigenMatrix solve_first = trainingSolver().solveColumns(first);
837 const double trace_adad =
838 backend().trace_product(solve_first, solve_first.transpose());
839 const Eigen::VectorXd v = first * alpha;
840 const Eigen::VectorXd z = trainingSolver().solve(v);
841
842 const double trace_ae = backend().trace_product(invC, second);
843
844 const double quad = v.dot(z);
845 const double alpha_e_alpha = alpha.dot(second * alpha);
846
847 const double curvature =
848 0.5 * (-trace_adad + trace_ae + 2.0 * quad - alpha_e_alpha) +
849 rigid_curvature + prior_curvature;
850 return std::isfinite(curvature)
851 ? curvature
852 : std::numeric_limits<double>::quiet_NaN();
853 };
854
855 // Layout of the flat probe vector (length n_probes = p(p+1)/2):
856 // [0 .. p) -> H(i, i) diagonal probes (one per i)
857 // [p .. p + p(p-1)/2) -> H(i, j) off-diagonal sum probes
858 // ordered (0,1), (0,2), .., (0,p-1),
859 // (1,2), .., (p-2, p-1).
860 const int n_diag = p;
861 const int n_off = p * (p - 1) / 2;
862 const int n_probes = n_diag + n_off;
863
864 auto direction_for_probe = [p, n_diag, &directions](int probe_idx) {
865 Eigen::VectorXd direction = Eigen::VectorXd::Zero(directions.rows());
866 if (probe_idx < n_diag) {
867 direction = directions.col(probe_idx);
868 return direction;
869 }
870
871 int off_idx = probe_idx - n_diag;
872 for (int i = 0; i < p; ++i) {
873 const int row_count = p - i - 1;
874 if (off_idx < row_count) {
875 const int j = i + 1 + off_idx;
876 direction = directions.col(i) + directions.col(j);
877 return direction;
878 }
879 off_idx -= row_count;
880 }
881
882 return direction;
883 };
884
885 const std::function<double(int)> probe_by_index = [&](int probe_idx) {
886 return probe(direction_for_probe(probe_idx));
887 };
888
889 linalg::MpiContext probe_ctx = linalg::MpiContext::local();
890 linalg::KernelInverse::Kind probe_kind =
892#ifdef GPR_LINALG_SCALAPACK
893 int mpi_up = 0;
894 MPI_Initialized(&mpi_up);
895 if (mpi_up) {
896 probe_ctx = mpiContext();
897 if (distributed_probes) {
899 }
900 }
901#endif
902
903 const linalg::ProbeExecutor probe_exec;
904 const Eigen::VectorXd probe_values =
905 probe_exec.run(n_probes, probe_by_index, probe_kind, probe_ctx);
906 if (report_level >= 1) {
907 log_man << "[laplace-curvature-work] streamed="
908 << training_geometry.streamed << " geometry_blocks="
909 << training_geometry.directional_geometry_blocks_for_testing
910 << " available_blocks=" << training_geometry.blocks.size()
911 << " probes=" << n_probes << "\n";
912 }
913 if (probe_values.size() != n_probes || !probe_values.allFinite()) {
914 return false;
915 }
916
917 // Assemble the symmetric H from the flat probe vector.
918 for (int i = 0; i < p; ++i) {
919 H(i, i) = probe_values(i);
920 }
921 int off_idx = 0;
922 for (int i = 0; i < p; ++i) {
923 for (int j = i + 1; j < p; ++j, ++off_idx) {
924 const double h_sum = probe_values(n_diag + off_idx);
925 const double h_ij = 0.5 * (h_sum - H(i, i) - H(j, j));
926 H(i, j) = h_ij;
927 H(j, i) = h_ij;
928 }
929 }
930
931 // The exact-Hessian assembly builds a self-contained objective basis for
932 // its directional probes. Drop it on exit so it is not a cross-call cache:
933 // each Laplace/SVGD fit (which re-runs assembleExactHessian) pays the same
934 // objective build, keeping the per-call SVGD wall flat instead of cheap
935 // after a one-time install. The Laplace predict path has its own posterior
936 // cache (ensureLaplacePosterior) and is unaffected; the MAP path assembles
937 // the Hessian once per fit, so no reuse is lost.
938 hssvd_objective_basis_valid_ = false;
939 clearHssvdPendingCovariance();
940 hssvd_objective_trace_via_cholesky_ = false;
941
942 return true;
943}
Eigen::VectorXd permuteTrainingVector(const Eigen::VectorXd &input) const
bool evaluateTrainingCovarianceMatrixFromGeometry(const TrainingKernelGeometry &geom, const EigenMatrix &x, const Eigen::VectorXd &x_ind, EigenMatrix &cov_matrix, bool serial_per_rank=false, bool include_constant=true, bool include_noise=true)
bool decomposeCovarianceMatrix(const EigenMatrix &x, const Eigen::VectorXd &x_ind)
Evaluate and decompose the covariance matrix using Cholesky decomposition.
bool evaluateDirectionalCurvature(const Eigen::VectorXd &x_ind, const EigenMatrix &x, const Eigen::VectorXd &y, const Eigen::VectorXd &direction, double &curvature, const TrainingKernelGeometry *training_geom=nullptr)
Evaluate the exact directional curvature p^T H p for the current GP objective state.
Definition Hessian.cpp:83
void calculateMeanPrediction(const Eigen::VectorXd &y)
Posterior mean prediction w.r.t energy. This function mimics the following step from the MATLAB code:...
Definition Predict.cpp:688
void prepareTrainingPermutation(const Eigen::VectorXd &x_ind)
linalg::linop::DenseCholeskySolver trainingSolver() const
std::pair< double, double > rigidNoiseDerivatives(const Eigen::VectorXd &direction) const
Definition Hessian.cpp:73
Eigen::Index activeFactorOrder(Eigen::Index full_rows) const noexcept
double trace_product(const EigenMatrix &A, const EigenMatrix &B)
EigenMatrix solveColumns(const EigenMatrix &B) const
K^{-1} B through the two triangular solves.
Eigen::VectorXd unwhiten(const Eigen::VectorXd &b) const
Eigen::VectorXd solve(const Eigen::VectorXd &y) const override
Eigen::VectorXd unpermuteVector(const Eigen::VectorXd &input, const StructuredPermutation &p)
EigenMatrix permuteSymmetricMatrix(const EigenMatrix &input, const StructuredPermutation &p)
EigenMatrix unpermuteMatrixRows(const EigenMatrix &input, const StructuredPermutation &p)
static void notePeak(const char *phase) noexcept

◆ assembleHssvdDualCrossCovarianceForTesting()

bool gpr::GaussianProcessRegression::assembleHssvdDualCrossCovarianceForTesting ( const EigenMatrix & positions,
EigenMatrix & Kstar,
Eigen::VectorXd & prior_diag,
bool energy_only ) const
inlinenodiscard

The dual-kernel cross covariance and prior diagonal that the HS-SVD variance routes contract; energy_only selects the energy columns the energy gate reads.

Definition at line 3078 of file GaussianProcessRegression.h.

3081 {
3082 return assembleHssvdDualCrossCovariance(positions, Kstar, &prior_diag,
3083 energy_only);
3084 }

◆ assembleHssvdDualFullCrossCovarianceForTesting()

bool gpr::GaussianProcessRegression::assembleHssvdDualFullCrossCovarianceForTesting ( const EigenMatrix & positions,
EigenMatrix & Kstar ) const
inlinenodiscard

Definition at line 3063 of file GaussianProcessRegression.h.

3065 {
3066 return assembleHssvdDualFullCrossCovariance(positions, Kstar, nullptr);
3067 }

◆ assembleHssvdDualTrainingKernelForTesting()

bool gpr::GaussianProcessRegression::assembleHssvdDualTrainingKernelForTesting ( EigenMatrix & kernel) const
inlinenodiscard

Definition at line 3085 of file GaussianProcessRegression.h.

3087 {
3088 return assembleHssvdDualTrainingKernel(hssvd_train_qtil_,
3089 hssvd_train_jtil_, kernel);
3090 }

◆ assembleLaplaceTrainingCovarianceFromGeometry()

bool gpr::GaussianProcessRegression::assembleLaplaceTrainingCovarianceFromGeometry ( const LaplaceTrainingCovarianceGeometry & geometry,
const Eigen::VectorXd & theta,
EigenMatrix & cov_matrix ) const
nodiscardprotected

Definition at line 278 of file LaplacePosterior.cpp.

281{
282 cov_matrix.resize(0, 0);
283 if (!geometry.valid || sexpat_cov_func == nullptr || theta.size() < 2 ||
284 geometry.rows <= 0 || geometry.indices.rows() != geometry.rows) {
285 return false;
286 }
287 const detail::ObservationChannelLayout layout(geometry.indices);
288 if (!layout.valid()) return false;
289
290 cov_matrix.resize(geometry.rows, geometry.rows);
291 cov_matrix.setZero();
292 addConstantCovarianceBlock(const_cov_fun.get(), geometry.indices,
293 geometry.indices, cov_matrix);
294
295 auto add_geometry_block =
296 [&](const Index_t row_value, const Index_t col_value,
297 const FieldMatrixd& field, const bool transpose_field) -> bool {
298 const auto row_block = layout.block(row_value);
299 const auto col_block = layout.block(col_value);
300 const Eigen::Index row_start = row_block.start;
301 const Eigen::Index row_count = row_block.count;
302 const Eigen::Index col_start = col_block.start;
303 const Eigen::Index col_count = col_block.count;
304 if (row_count <= 0 || col_count <= 0 ||
305 row_start + row_count > cov_matrix.rows() ||
306 col_start + col_count > cov_matrix.cols()) {
307 return false;
308 }
309 if (!transpose_field) {
310 if (field.rows() < row_count || field.cols() < col_count) {
311 return false;
312 }
313 cov_matrix.block(row_start, col_start, row_count, col_count)
314 .noalias() += field.block(0, 0, row_count, col_count);
315 } else {
316 if (field.rows() < col_count || field.cols() < row_count) {
317 return false;
318 }
319 cov_matrix.block(row_start, col_start, row_count, col_count)
320 .noalias() +=
321 field.block(0, 0, col_count, row_count).transpose();
322 }
323 return true;
324 };
325
326 FieldMatrixd block_covariance;
327 for (const auto& block: geometry.blocks) {
328 if (!sexpat_cov_func->evaluateCrossBlockGeometry(block.sexpat, theta,
329 block_covariance)) {
330 return false;
331 }
332 if (!add_geometry_block(block.row_value, block.col_value,
333 block_covariance,
334 /*transpose_field=*/false)) {
335 return false;
336 }
337 if (block.has_transpose_mirror) {
338 if (!add_geometry_block(block.mirror_row_value,
339 block.mirror_col_value, block_covariance,
340 /*transpose_field=*/true)) {
341 return false;
342 }
343 }
344 }
345
346 double noise = lik_gaussian != nullptr ? lik_gaussian->getSigma2() : 0.0;
347 const Eigen::Index n_cov = covarianceParameterCount();
348 if (theta_includes_likelihood_noise_ && n_cov > 0 && theta.size() > n_cov) {
349 noise = std::exp(theta(theta.size() - 1));
350 }
351 if (noise != 0.0) cov_matrix.diagonal().array() += noise;
352 return true;
353}

◆ assignBlockToMatrix()

void gpr::GaussianProcessRegression::assignBlockToMatrix ( const Eigen::VectorXd & ind_Ddim1,
const Eigen::VectorXd & ind_Ddim2,
const Index_t row_val,
const Index_t col_val,
const FieldMatrixd & field,
EigenMatrix & matrix,
bool transpose_field = false ) const

Assign field to matrix according to indices form ind_Ddim1 and ind_Ddim2.

This function performs the following operation (in MATLAB form):

\[ matrix(ind_Ddim == row_val, ind_Ddim == col_val) = field; \]

Note
matrix should be pre-allocated
Parameters
ind_Ddim1Vector of dimensions used in rows
ind_Ddim2Vector of dimensions used in columns
row_valIndex of row
col_valIndex of column
fieldReference field
matrixReference matrix
transpose_fieldTrue if the field should be transposed

Definition at line 2692 of file CovarianceAssembly.cpp.

2696{
2697 const auto row_block = observationChannelBlock(ind_Ddim1, row_val);
2698 const auto col_block = observationChannelBlock(ind_Ddim2, col_val);
2699 const Eigen::Index i_start = row_block.start;
2700 const Eigen::Index j_start = col_block.start;
2701 const Eigen::Index block_rows = row_block.count;
2702 const Eigen::Index block_cols = col_block.count;
2703
2704 if (!transpose_field) {
2705 matrix.block(i_start, j_start, block_rows, block_cols) =
2706 field.block(0, 0, block_rows, block_cols);
2707 } else {
2708 matrix.block(i_start, j_start, block_rows, block_cols) =
2709 field.block(0, 0, block_cols, block_rows).transpose();
2710 }
2711}

◆ atomicEnvironmentInducingCount()

Eigen::Index gpr::GaussianProcessRegression::atomicEnvironmentInducingCount ( ) const
nodiscard

Definition at line 273 of file AtomicEnvironment.cpp.

274{
276 ? atomic_environment_posterior_->inducingCount()
277 : 0;
278}

◆ atomicEnvironmentModelEnabled()

bool gpr::GaussianProcessRegression::atomicEnvironmentModelEnabled ( ) const
inlinenodiscardnoexcept

Definition at line 447 of file GaussianProcessRegression.h.

448 {
449 return atomic_environment_model_;
450 }

◆ atomicEnvironmentParameterState()

GaussianProcessRegression::AtomicEnvironmentParameterState gpr::GaussianProcessRegression::atomicEnvironmentParameterState ( ) const
nodiscard

Definition at line 281 of file AtomicEnvironment.cpp.

282{
283 if (!atomic_environment_model_) return {};
284 return {true, atomic_environment_parameter_species_,
285 atomic_environment_parameters_};
286}

◆ atomicEnvironmentPosteriorBuilt()

bool gpr::GaussianProcessRegression::atomicEnvironmentPosteriorBuilt ( ) const
nodiscard

Definition at line 253 of file AtomicEnvironment.cpp.

254{
255 return atomic_environment_model_ && atomic_environment_posterior_ &&
256 atomic_environment_posterior_->built() &&
257 !use_chem_factorized_hyper_ &&
258 uncertainty_mode_ == UncertaintyMode::MAP &&
259 hyperparameter_objective_mode_ ==
261 hyperparameter_optimization_mode_ !=
263 lik_gaussian && !lik_gaussian->getOptimizeSigma2() &&
264 robust_nu_ == 0.0 &&
265 atomic_environment_likelihood_sigma2_ == lik_gaussian->getSigma2() &&
266 atomic_environment_noise_revision_ ==
267 lik_gaussian->geometryNoiseRevision() &&
268 atomic_environment_zbl_mean_ == use_zbl_prior_mean_ &&
269 atomic_environment_ff_mean_ == use_ff_prior_mean_ &&
270 atomic_environment_prior_mean_statistic_ == prior_mean_statistic_;
271}

◆ backend()

linalg::BackendContext & gpr::GaussianProcessRegression::backend ( ) const
inlinenodiscardprotected

Definition at line 5285 of file GaussianProcessRegression.h.

5286 {
5287 return *backend_context_;
5288 }

◆ bandInfluenceFactorReusesForTesting()

std::size_t gpr::GaussianProcessRegression::bandInfluenceFactorReusesForTesting ( ) const
inlinenodiscardnoexcept

Definition at line 2768 of file GaussianProcessRegression.h.

2770 {
2771 return band_influence_factor_reuses_for_testing_;
2772 }

◆ buildLaplaceTrainingCovarianceGeometry()

bool gpr::GaussianProcessRegression::buildLaplaceTrainingCovarianceGeometry ( const EigenMatrix & x,
const Eigen::VectorXd & x_ind,
LaplaceTrainingCovarianceGeometry & geometry ) const
nodiscardprotected

Definition at line 178 of file LaplacePosterior.cpp.

181{
183 if (sexpat_cov_func == nullptr || x.rows() <= 0 ||
184 x.rows() != x_ind.rows() || x.cols() < 2) {
185 return false;
186 }
187
188 geometry.indices = x_ind;
189 geometry.rows = x.rows();
190 geometry.repetitive_block_size = getNumberOfRepetitiveIndices(x_ind);
191 if (geometry.repetitive_block_size <= 0) return false;
192 extractUniqueIndices(x_ind, geometry.unique_derivative_indices);
193
194 Eigen::Map<const Eigen::ArrayXd> ind_array(x_ind.data(), x_ind.size());
195 FieldMatrixd x_loc_0, x_loc_1, x_loc_2;
196 FieldMatrixIdx dims1(1, 1), dims2(1, 1);
197 x_loc_0.resize((Index_t)(ind_array == 0).count(), (Index_t)x.cols() + 1);
198 x_loc_0.setZero();
199 if (x_loc_0.rows() <= 0) return false;
200 extractCoordinatesByIndex(x, x_ind, 0, x_loc_0);
201
202 auto append_block =
203 [&](const FieldMatrixd& left, const FieldMatrixd& right,
204 const Index_t row_value, const Index_t col_value,
205 const FieldMatrixIdx& left_dims, const FieldMatrixIdx& right_dims,
206 const uint8_t derivative_options, const bool has_transpose_mirror,
207 const Index_t mirror_row_value,
208 const Index_t mirror_col_value) -> bool {
210 block.row_value = row_value;
211 block.col_value = col_value;
212 block.has_transpose_mirror = has_transpose_mirror;
213 block.mirror_row_value = mirror_row_value;
214 block.mirror_col_value = mirror_col_value;
215 if (!sexpat_cov_func->buildCrossBlockGeometry(
216 left, right, derivative_options, left_dims, right_dims,
217 block.sexpat)) {
218 return false;
219 }
220 geometry.blocks.push_back(std::move(block));
221 return true;
222 };
223
224 if (!append_block(x_loc_0, x_loc_0, 0, 0, dims1, dims2, 0,
225 /*has_transpose_mirror=*/false, 0, 0)) {
226 return false;
227 }
228
229 for (Index_t n = 0; n < geometry.unique_derivative_indices.size(); ++n) {
230 const Index_t row_value =
231 static_cast<Index_t>(geometry.unique_derivative_indices[n]);
232 dims1(0, 0) = row_value;
233 x_loc_1.resize((Index_t)(ind_array == row_value).count(),
234 (Index_t)x.cols() + 1);
235 x_loc_1.setZero();
236 extractCoordinatesByIndex(x, x_ind, row_value, x_loc_1);
237 if (x_loc_1.rows() <= 0) return false;
238
239 if (!append_block(x_loc_1, x_loc_0, row_value, 0, dims1, dims2,
241 /*has_transpose_mirror=*/true, 0, row_value)) {
242 return false;
243 }
244
245 if (!append_block(
246 x_loc_1, x_loc_1, row_value, row_value, dims1, dims1,
249 /*has_transpose_mirror=*/false, row_value, row_value)) {
250 return false;
251 }
252
253 for (Index_t m = n + 1; m < geometry.unique_derivative_indices.size();
254 ++m) {
255 const Index_t col_value =
256 static_cast<Index_t>(geometry.unique_derivative_indices[m]);
257 dims2(0, 0) = col_value;
258 x_loc_2.resize((Index_t)(ind_array == col_value).count(),
259 (Index_t)x.cols() + 1);
260 x_loc_2.setZero();
261 extractCoordinatesByIndex(x, x_ind, col_value, x_loc_2);
262 if (x_loc_2.rows() <= 0) return false;
263 if (!append_block(
264 x_loc_1, x_loc_2, row_value, col_value, dims1, dims2,
268 /*has_transpose_mirror=*/true, col_value, row_value)) {
269 return false;
270 }
271 }
272 }
273
274 geometry.valid = true;
275 return true;
276}
@ D12
Definition Enums.h:21
@ D2
Definition Enums.h:20

◆ buildRFFModel()

void gpr::GaussianProcessRegression::buildRFFModel ( const Observation & training_data,
int D_rff )

Random Fourier Features (RFF) layered predict path. Approximates the SE kernel with D_rff random cosine features, then solves Bayesian linear regression in the feature space. Per-call predict cost drops from O(N (D+1)) (cached MAP cross-cov + matvec) to O(D_rff D) (constant in N). Layered ON TOP of the LAPLACE_SLICE + INLA-Delta variance: the RFF mean replaces the cheap-mean MAP path; INLA-Delta still provides the calibrated variance for the gate. D_rff = 0 disables RFF (default; bit-identical to main).

Definition at line 17 of file RFF.cpp.

19{
20 // Layered RFF predict: build the random-feature model on the
21 // SCG-trained kernel hyperparameters. Per-fit cost O(N D D_rff +
22 // D_rff^3), per-predict cost O(D_rff D) -- constant in N. The
23 // LAPLACE_SLICE arm's INLA-Delta variance is unchanged; only the
24 // predict-mean cost path is replaced. Caller is expected to call
25 // this after optimize() so magnSigma2 / lengthScale are set, and
26 // before the first calculatePotentialRFF.
27 // ChemGP-tuned BLR noise: noise_e = 1e-6, noise_g = 1e-4 (per
28 // crates/chemgp-core/src/predict.rs build_pred_model defaults).
29 // The C++ GPR's sigma2 / jitter_sigma2 are tuned for the exact-GP
30 // Cholesky (typically sigma2 ~ 1e-7, jitter ~ 1e-6) which is too
31 // tight for the RFF BLR -- the Bayesian posterior mean overfits
32 // the random features and produces noisy gradient predictions
33 // that the dimer's curvature finite-difference step turns into
34 // NaN. Floor the noise at the ChemGP-validated values; if the
35 // GP's own noise estimate is larger (rare), use that.
36 // Defensive: if SCG drifted sigma2 / jitter_sigma2 to non-finite or
37 // negative values, std::max(NaN, x) returns NaN under libstdc++ and
38 // bakes the NaN into the BLR posterior. Substitute the floor before
39 // taking max so the floor is the worst case. The floors live in
40 // rffObservationNoise so the automatic selector uses the same ones.
41 double rff_noise_e = 0.0;
42 double rff_noise_g = 0.0;
43 rffObservationNoise(rff_noise_e, rff_noise_g);
44 // The random-feature regression fits the residual about the prior
45 // mean (ZBL when active), exactly as the exact posterior does; the mean
46 // is added back in calculatePotentialRFF. Without this the RFF model
47 // could not be used under the ZBL prior mean at all. A fixed count
48 // trains on physical residuals. Automatic selection uses the
49 // standardized builder and sets rff_standardized_targets_.
50 const Observation residual = rffResidualObservation(training_data);
51 rff_standardized_targets_ = false;
52 rff_model_.build(*sexpat_cov_func, atoms_config, residual, D_rff,
53 rff_noise_e, rff_noise_g);
54 PhaseTimers::notePeak("rff_build");
55 rff_features_ = D_rff;
56}

◆ calculateBackgroundObservationPosteriorCrossCovariance()

void gpr::GaussianProcessRegression::calculateBackgroundObservationPosteriorCrossCovariance ( const EigenMatrix & left,
const EigenMatrix & right,
EigenMatrix & covariance,
const Eigen::VectorXd * mean_weights = nullptr )

Posterior cross covariance of the joint channels of left against right, or its contraction with mean_weights; public for the tests of the subset-conditioned posterior.

Definition at line 905 of file Variance.cpp.

909{
910 if (left.cols() != right.cols() || !left.allFinite() || !right.allFinite())
911 throw std::invalid_argument(
912 "invalid posterior cross-covariance geometry");
913 const Eigen::Index channels = left.cols() + 1;
914 if (mean_weights && (mean_weights->size() != right.rows() * channels ||
915 !mean_weights->allFinite()))
916 throw std::invalid_argument("invalid posterior mean coefficients");
917 if (left.rows() == 0 || right.rows() == 0) {
918 covariance = EigenMatrix::Zero(
919 left.rows() * channels, mean_weights ? 1 : right.rows() * channels);
920 return;
921 }
922 const double variance_scale2 = checkedOutputVarianceScaleSquared();
923 if (detail::matrixExactlyEqual(left, right)) {
924 calculateBackgroundObservationPosteriorCovariance(left, covariance,
925 false);
926 if (mean_weights) covariance = (covariance * *mean_weights).eval();
927 return;
928 }
929 ensurePosteriorFactorForPrediction();
930 const bool spectral = canUseHssvdVariance();
931 // Coincident training channels use the statistical-noise identity below.
932 // Its entrywise corrections precede contraction with the fitted weights.
933 const bool training_pair =
934 spectral && mean_weights &&
935 ((hssvdTrainingChannelsForQueries(left).array() >= 0).any() ||
936 (hssvdTrainingChannelsForQueries(right).array() >= 0).any());
937 const bool contract = mean_weights && !training_pair;
938 aux::AuxiliaryFunctionality layout;
939 EigenMatrix left_rows, right_rows;
940 Eigen::VectorXd left_indices, right_indices;
941 layout.assembleMatrixOfRepetitiveCoordinates(left, left_rows, left_indices);
942 layout.assembleMatrixOfRepetitiveCoordinates(right, right_rows,
943 right_indices);
944 EigenMatrix prior;
945 evaluateCovarianceMatrix(left_rows, right_rows, left_indices, right_indices,
946 prior, /*serial_per_rank=*/true);
947 if (contract) prior = (prior * *mean_weights).eval();
948 covariance = prior;
949
950 // Each cross block conditions on the same retained background. The
951 // query self-covariance and residual self-covariance are unnecessary for
952 // K(left,right | training) and for its contraction in the active mean.
953 const auto training_cross = [&](const EigenMatrix& positions,
954 const EigenMatrix& rows,
955 const Eigen::VectorXd& indices,
956 EigenMatrix& cross, bool spectral) {
957 if (!spectral ||
958 !assembleHssvdDualFullCrossCovariance(positions, cross, nullptr)) {
959 evaluateCovarianceMatrix(R_matrix, rows, R_indices, indices, cross,
960 /*serial_per_rank=*/true);
961 }
962 };
963 if (spectral) {
964 EigenMatrix left_cross, right_cross;
965 training_cross(left, left_rows, left_indices, left_cross, true);
966 training_cross(right, right_rows, right_indices, right_cross, true);
967 if (contract) right_cross = (right_cross * *mean_weights).eval();
968 const double noise = totalPosteriorNoiseVariance();
970 hssvd_basis_, left_cross, right_cross, prior, noise, covariance,
971 contract, left.rows(), right.rows())) {
972 if (!contract)
973 applyHssvdTrainingRowLatentCrossCovariance(left, right,
974 covariance, noise);
976 throw linalg::StableVarianceError(
977 "stable posterior cross covariance: the HS-SVD cross "
978 "covariance does not match the basis");
979 } else {
980 covariance = prior;
981 }
982 } else if (hasTrainingCholeskyFactor(R_matrix.rows()) &&
983 prepareVarianceSubset(left)) {
984 // Conditioned on the subset chosen for the left query (the active
985 // posterior asks for the cross covariance between a query and
986 // every active row; the full solve was 1.9 s per band outer on
987 // oxirane).
988 EigenMatrix left_cross, right_cross;
989 if (!varianceSubsetCrossCovariance(left_rows, left_indices,
990 left_cross) ||
991 !varianceSubsetCrossCovariance(right_rows, right_indices,
992 right_cross))
993 throw std::runtime_error("variance subset cross covariance failed");
994 ++variance_subset_queries_;
995 if (contract) right_cross = (right_cross * *mean_weights).eval();
996 subtractCholeskyCrossCovariance(
997 {*variance_subset_backend_, variance_subset_factor_}, left_cross,
998 right_cross, covariance);
999 } else if (hasTrainingCholeskyFactor(R_matrix.rows())) {
1000 EigenMatrix left_cross, right_cross;
1001 training_cross(left, left_rows, left_indices, left_cross, false);
1002 training_cross(right, right_rows, right_indices, right_cross, false);
1003 left_cross = permuteTrainingRows(left_cross);
1004 if (contract) {
1005 right_cross = permuteTrainingRows(right_cross * *mean_weights);
1006 } else {
1007 right_cross = permuteTrainingRows(right_cross);
1008 }
1009 if (rigid_deflation_.isActiveForFullOrder(left_cross.rows())) {
1010 left_cross = rigid_deflation_.projectRows(left_cross);
1011 right_cross = rigid_deflation_.projectRows(right_cross);
1012 }
1013 if (contract) {
1014 const Eigen::VectorXd action =
1015 trainingSolver().solve(right_cross.col(0));
1016 covariance.col(0).noalias() -= left_cross.transpose() * action;
1017 covariance *= variance_scale2;
1018 return;
1019 }
1020 subtractCholeskyCrossCovariance(trainingSolver(), left_cross,
1021 right_cross, covariance);
1022 }
1023 covariance *= variance_scale2;
1024 if (mean_weights && !contract)
1025 covariance = (covariance * *mean_weights).eval();
1026}
void assembleMatrixOfRepetitiveCoordinates(const gpr::Coord &coord, gpr::EigenMatrix &matrix, Eigen::VectorXd &ind)
Assemble Eigen matrix with repetitive rows based on provided set of coordinates R.
void evaluateCovarianceMatrix(const EigenMatrix &x1, const EigenMatrix &x2, const Eigen::VectorXd &x1_ind, const Eigen::VectorXd &x2_ind, EigenMatrix &C, bool serial_per_rank=false) const
Evaluate covariance matrix between two input vectors.
EigenMatrix permuteTrainingRows(const EigenMatrix &input) const
bool stablePosteriorVarianceEnabled() noexcept
Whether stable posterior variance reductions are enabled.
Definition ExactSchur.h:40
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)

◆ calculateExactDirectionalCurvature()

bool gpr::GaussianProcessRegression::calculateExactDirectionalCurvature ( const Coord & R,
const Eigen::VectorXd & direction,
double & curvature )
nodiscard

Directional curvature v^T H_mu(R) v of the posterior mean. True when the contraction is analytic. Exactness is KernelOperator::meanCurvature. A pullback is Exact when its chart provides a directional Jacobian, a conditioned kernel reports its child (so conditioned geodesic heat is Exact), and a sum is Exact only when every summand is. That classification also admits an inverse-distance Sexpat mean, an exact active-posterior background and residual, and a spectral block. A mean that is not Exact, and an exact operator that refuses the query, returns false and leaves curvature NaN. The predicted-gradient stencil is not a substitute.

Definition at line 2940 of file ActivePosterior.cpp.

2942{
2943 curvature = std::numeric_limits<double>::quiet_NaN();
2944 if (atomic_environment_model_ || R.rows() != 1 || R.cols() == 0 ||
2945 direction.size() != R.cols() || !R.allFinite() ||
2946 !direction.allFinite())
2947 return false;
2948 // Laplace, SVGD, and BMA predictive means are factor mixtures. The
2949 // HS-SVD and MAP kernel contractions below differentiate the MAP mean
2950 // only, so they are not this mean's curvature.
2951 if (!active_posterior_ && (uncertainty_mode_ == UncertaintyMode::LAPLACE ||
2952 uncertainty_mode_ == UncertaintyMode::SVGD ||
2953 uncertainty_mode_ == UncertaintyMode::BMA))
2954 return false;
2955
2956 const Eigen::VectorXd position = R.row(0).transpose();
2957 // The caller already holds the contraction. Rebuilding the dense matrix
2958 // here would replace an exact action with a second assembly.
2959 auto finish = [&](const Eigen::VectorXd& hessian_vector) {
2960 if (hessian_vector.size() != direction.size() ||
2961 !hessian_vector.allFinite())
2962 return false;
2963 const double value = direction.dot(hessian_vector);
2964 if (!std::isfinite(value)) return false;
2965 curvature = value;
2966 return true;
2967 };
2968 auto add_prior = [&](Eigen::VectorXd& hessian_vector) {
2969 if (ffPriorMeanActive())
2970 hessian_vector += priors::applyPriorHessianPairs(
2971 ff_prior_mean_->hessianPairs(R.row(0)), direction);
2972 else if (zblPriorMeanActive())
2973 hessian_vector += priors::applyPriorHessianPairs(
2974 zbl_prior_mean_->hessianPairs(R.row(0)), direction);
2975 };
2976
2977 const auto mean_is_exact = [](const KernelOperator& kernel) {
2978 return kernel.meanCurvature() == KernelOperator::MeanCurvature::Exact;
2979 };
2980 // Ownership is the kernel's meanCurvature, not whether
2981 // prepareMeanHessian is non-empty. A pullback with a directional
2982 // Jacobian is Exact, and ConditionedKernel reports its child, so
2983 // conditioned geodesic heat is Exact too. Inverse-distance Sexpat has
2984 // no assembled chart or heat operator and reports Exact itself.
2985 const auto background_is_exact = [&] {
2986 if (!sexpat_cov_func) return false;
2987 if (const auto kernel = sexpat_cov_func->assembledOperator())
2988 return mean_is_exact(*kernel);
2989 const Sexpat inverse_distance(*sexpat_cov_func);
2990 return mean_is_exact(inverse_distance);
2991 };
2992
2993 // An active posterior owns the mean. A residual or background that is
2994 // not Exact cannot be replaced by a stencil here.
2995 if (active_posterior_) {
2996 if (active_posterior_->mean_weights.size() == 0) return false;
2997 requireActivePosteriorBackground();
2998 const auto& state = *active_posterior_;
2999 if (!state.background_hessian_refusal || !background_is_exact() ||
3000 (state.kernel && (!state.residual_hessian_refusal ||
3001 !mean_is_exact(*state.kernel))))
3002 return false;
3003 // One direction, one action. The stored matrix functions walk every
3004 // Cartesian axis and are the dense assembly this query does not make.
3005 bool refused = false;
3006 const auto background =
3007 state.background_hessian_refusal(position, refused);
3008 const auto residual =
3009 state.kernel ? state.residual_hessian_refusal(position, refused)
3011 if (refused || !background || (state.kernel && !residual)) return false;
3012 Eigen::VectorXd hessian_vector;
3013 if (!background(direction, hessian_vector, refused) || refused ||
3014 hessian_vector.size() != direction.size())
3015 return false;
3016 if (residual) {
3017 Eigen::VectorXd term;
3018 if (!residual(direction, term, refused) || refused ||
3019 term.size() != direction.size())
3020 return false;
3021 hessian_vector += term;
3022 }
3023 add_prior(hessian_vector);
3024 return finish(hessian_vector);
3025 }
3026
3027 // Chart and geodesic means are not the inverse-distance Sexpat Hessian.
3028 // Exactness is the assembled operator's meanCurvature. A query the
3029 // operator refuses stays refused; it is not replaced by a stencil.
3030 if (sexpat_cov_func && (sexpat_cov_func->usesManifoldChart() ||
3031 sexpat_cov_func->usesGeodesicHeatKernel())) {
3033 uncertainty_mode_ != UncertaintyMode::MAP ||
3034 R_matrix.rows() != a.size() || R_matrix.cols() < R.cols() ||
3035 a.size() == 0 || a.size() % (R.cols() + 1) != 0)
3036 return false;
3037 const Eigen::Index count = a.size() / (R.cols() + 1);
3038 const Coord training = R_matrix.topRows(count).leftCols(R.cols());
3039 const Eigen::VectorXd weights = y_scale_ * unpermuteTrainingVector(a);
3040 const auto kernel = sexpat_cov_func->assembledOperator();
3041 if (!kernel || !mean_is_exact(*kernel)) return false;
3042 Eigen::VectorXd hessian_vector;
3043 bool applied = false;
3044 try {
3045 applied = kernel->meanHessianVector(training, weights, position,
3046 direction, hessian_vector);
3047 } catch (const geometry::UndefinedInternalCoordinate&) {
3048 return false;
3049 }
3050 if (!applied) return false;
3051 add_prior(hessian_vector);
3052 return finish(hessian_vector);
3053 }
3054
3055 // A dual HS-SVD model and the MAP kernel expansion share one mean. The
3056 // spectral contraction takes precedence, as in calculateMeanHessian,
3057 // unless a MAP test kernel overrides it.
3058 if (!optimizer_state_->mean_hessian.map_kernel_overrides_hssvd) {
3059 Eigen::VectorXd hessian_vector;
3060 switch (meanHessianProductHssvd(R, direction, hessian_vector)) {
3062 return finish(hessian_vector);
3064 return false;
3066 break;
3067 }
3068 }
3069 if (Eigen::VectorXd weights;
3070 auto kernel = mapSexpatMeanKernel(R.cols(), weights)) {
3071 if (!mean_is_exact(*kernel)) return false;
3072 auto prepare = makeRefusalAwareKernelMeanHessian(
3073 kernel, full_fit_observations_.R, weights);
3074 bool refused = false;
3075 const auto action = prepare(position, refused);
3076 Eigen::VectorXd hessian_vector;
3077 if (refused || !action || !action(direction, hessian_vector, refused) ||
3078 refused || hessian_vector.size() != direction.size())
3079 return false;
3080 add_prior(hessian_vector);
3081 return finish(hessian_vector);
3082 }
3083 return false;
3084}
Eigen::VectorXd unpermuteTrainingVector(const Eigen::VectorXd &input) const
std::function< bool( const Eigen::VectorXd &, Eigen::VectorXd &, bool &exact_refusal)> RefusalAwareHessianAction
Hessian action that reports whether an exact child refused.
FieldMatrixd Coord
Definition Macros.h:35
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...
Panel finish(Real left, Real right, const Value &k, const Value &g, const Value &absolute)

◆ calculateInlaModeLogBounds()

void gpr::GaussianProcessRegression::calculateInlaModeLogBounds ( const Eigen::VectorXd & theta_seed,
double min_lengthscale,
double max_log_magn_sigma2,
Eigen::VectorXd & lower,
Eigen::VectorXd & upper ) const
protected

Definition at line 180 of file INLA.cpp.

184{
185 lower.resize(0);
186 upper.resize(0);
187 if (theta_seed.size() == 0 || sexpat_cov_func == nullptr) return;
188
189 lower.resize(theta_seed.size());
190 upper.resize(theta_seed.size());
191
192 const PriorBase amplitude_prior =
193 sexpat_cov_func->getPriorParametersSqrtt();
194 const double amplitude_scale2 =
195 (amplitude_prior.getS2() > 0.0) ? amplitude_prior.getS2() : 1.0;
196 lower(0) = std::log(std::max(1.0e-12, 1.0e-6 * amplitude_scale2));
197 upper(0) = max_log_magn_sigma2;
198 if (lower(0) >= upper(0)) lower(0) = upper(0) - std::log(1.0e6);
199
200 const PriorBase length_prior =
201 sexpat_cov_func->getPriorParametersGaussian();
202 const double prior_length_scale =
203 (length_prior.getS2() > 0.0) ? std::sqrt(length_prior.getS2()) : 1.0;
204 const double length_center = std::abs(length_prior.getMu());
205 const double lower_length = std::max(1.0e-6, min_lengthscale);
206 const double upper_length =
207 std::max({10.0 * lower_length,
208 length_center + 30.0 * prior_length_scale, 1.0e-2});
209
210 const bool has_noise = hasTrailingLikelihoodNoiseParameter(theta_seed);
211 const Eigen::Index length_end =
212 has_noise ? theta_seed.size() - 1 : theta_seed.size();
213 for (Eigen::Index i = 1; i < length_end; ++i) {
214 lower(i) = std::log(lower_length);
215 upper(i) = std::log(upper_length);
216 if (lower(i) >= upper(i)) lower(i) = upper(i) - std::log(1.0e6);
217 }
218
219 if (has_noise) {
220 const Eigen::Index noise_idx = theta_seed.size() - 1;
221 const double seed_noise = std::exp(theta_seed(noise_idx));
222 const double lower_noise =
223 std::max(1.0e-12, std::min(seed_noise * 1.0e-4, 1.0e-8));
224 const double upper_noise =
225 std::max({1.0e-2, seed_noise * 1.0e4, lower_noise * 1.0e6});
226 lower(noise_idx) = std::log(lower_noise);
227 upper(noise_idx) = std::log(upper_noise);
228 if (lower(noise_idx) >= upper(noise_idx)) {
229 lower(noise_idx) = upper(noise_idx) - std::log(1.0e6);
230 }
231 }
232}

◆ calculateInlaModeLogBoundsForTesting()

void gpr::GaussianProcessRegression::calculateInlaModeLogBoundsForTesting ( const Eigen::VectorXd & theta_seed,
double min_lengthscale,
const EigenMatrix & x,
const Eigen::VectorXd & y,
Eigen::VectorXd & lower,
Eigen::VectorXd & upper ) const
inline

Definition at line 3037 of file GaussianProcessRegression.h.

3043 {
3044 calculateInlaModeLogBounds(theta_seed, min_lengthscale,
3045 inlaMaxLogMagnSigma2(x, y, theta_seed),
3046 lower, upper);
3047 }
void calculateInlaModeLogBounds(const Eigen::VectorXd &theta_seed, double min_lengthscale, double max_log_magn_sigma2, Eigen::VectorXd &lower, Eigen::VectorXd &upper) const
Definition INLA.cpp:180
double inlaMaxLogMagnSigma2(const EigenMatrix &x, const Eigen::VectorXd &y, const Eigen::VectorXd &theta_seed) const
Definition INLA.cpp:164

◆ calculateLaplaceMixtureMeanHessianVector()

GaussianProcessRegression::MixtureMeanHessianStatus gpr::GaussianProcessRegression::calculateLaplaceMixtureMeanHessianVector ( const Coord & R,
const Eigen::VectorXd & direction,
Eigen::VectorXd & hessian_vector )
nodiscard

Weighted sum of exact pair-kernel Hessian-vector products at the cached Laplace factors, including the block-assembled mean. NotApplicable when the predictive mean is not that mixture. Refused when the mixture is the mean and a factor contraction fails.

Definition at line 1223 of file LaplacePosterior.cpp.

1226{
1227 hessian_vector.resize(0);
1228 const Eigen::Index dof = R.cols();
1229 if (uncertainty_mode_ != UncertaintyMode::LAPLACE ||
1230 atomic_environment_model_ || active_posterior_ ||
1231 sexpat_cov_func == nullptr || R.rows() != 1 ||
1232 direction.size() != dof || dof <= 0 || !R.allFinite() ||
1233 !direction.allFinite())
1235 if (!ensureLaplacePosterior() || !laplace_posterior_ ||
1236 !laplace_posterior_->valid)
1237 return calculateMapFallbackMeanHessianVector(R, direction,
1238 hessian_vector);
1239 // The block assembly and the alpha-K contraction are the same mean.
1240 // Both are differentiated here; a factor that cannot be contracted
1241 // refuses instead of falling through to a difference.
1242 return contractFactorMixtureMeanHessian(*laplace_posterior_, R, direction,
1243 hessian_vector);
1244}

◆ calculateMeanHessian()

bool gpr::GaussianProcessRegression::calculateMeanHessian ( const Coord & R,
Eigen::MatrixXd & hessian )
nodiscard

Dense Hessian of the physical posterior mean at one geometry.

The sources are tried in this order. An active posterior whose background and residual are both exact assembles their matrices, and a refusal is final. Otherwise, outside an atomic environment or an active posterior, a prepared HS-SVD block applied to the identity is the matrix, before any exact MAP kernel is consulted; a failed apply returns false and leaves the matrix empty, and the action columns and the stencil are not substitutes. When that block is not prepared, the MAP kernel assembles its matrix from its refusal-aware action. A refusal by an exact term is final. A generic term without an analytic contraction is not a refusal: the matrix is then the columns of prepareMeanHessian(R), whose generic miss uses the stencil of the mean gradient.

Definition at line 2845 of file ActivePosterior.cpp.

2847{
2848 hessian.resize(0, 0);
2849 if (R.rows() != 1 || R.cols() == 0 || !R.allFinite()) return false;
2850 const Eigen::Index dof = R.cols();
2851 const Eigen::VectorXd position = R.row(0).transpose();
2852 const auto columns = [dof](const MeanHessianAction& action,
2853 Eigen::MatrixXd& result) {
2854 if (!action) return false;
2855 result.resize(dof, dof);
2856 Eigen::VectorXd column;
2857 for (Eigen::Index j = 0; j < dof; ++j) {
2858 if (!action(Eigen::VectorXd::Unit(dof, j), column) ||
2859 column.size() != dof)
2860 return false;
2861 result.col(j) = column;
2862 }
2863 return true;
2864 };
2866 // A computed kernel matrix takes the physical prior; a refusal is final.
2867 // Unavailable leaves the matrix to the action columns below, whose
2868 // generic miss reaches the stencil.
2869 const auto finish_kernel_matrix =
2870 [&](Status status) -> std::optional<bool> {
2871 if (status == Status::Unavailable) return std::nullopt;
2872 if (status == Status::Computed && hessian.rows() == dof &&
2873 hessian.cols() == dof) {
2874 if (ffPriorMeanActive())
2876 ff_prior_mean_->hessianPairs(R.row(0)), hessian);
2877 else if (zblPriorMeanActive())
2879 zbl_prior_mean_->hessianPairs(R.row(0)), hessian);
2881 const Eigen::MatrixXd& secant = secantQuadraticHessian();
2882 if (secant.rows() != dof || secant.cols() != dof) {
2883 hessian.resize(0, 0);
2884 return false;
2885 }
2886 hessian += secant;
2887 }
2888 if (hessian.allFinite()) return true;
2889 }
2890 hessian.resize(0, 0);
2891 return false;
2892 };
2893 if (!atomic_environment_model_ && active_posterior_ &&
2894 active_posterior_->mean_weights.size() > 0 &&
2895 active_posterior_->background_hessian) {
2896 requireActivePosteriorBackground();
2897 const auto& state = *active_posterior_;
2898 if (state.background_hessian_exact &&
2899 (!state.kernel || state.residual_hessian_exact)) {
2900 Status status = state.background_hessian_matrix(position, hessian);
2901 if (status == Status::Computed && state.kernel) {
2902 Eigen::MatrixXd residual;
2903 status = state.residual_hessian_matrix(position, residual);
2904 if (status == Status::Computed) hessian += residual;
2905 }
2906 if (const auto done = finish_kernel_matrix(status)) return *done;
2907 }
2908 }
2909 if (!atomic_environment_model_ && !active_posterior_ &&
2910 !optimizer_state_->mean_hessian.map_kernel_overrides_hssvd) {
2912 if (prepareMeanHessianVectorHssvd(R, prepared)) {
2914 prepared, Eigen::MatrixXd::Identity(dof, dof), hessian) &&
2915 hessian.rows() == dof && hessian.cols() == dof &&
2916 hessian.allFinite())
2917 return true;
2918 // A prepared block that does not apply has refused. The action
2919 // columns, and the stencil behind them, are not a substitute.
2920 hessian.resize(0, 0);
2921 return false;
2922 }
2923 }
2924 if (Eigen::VectorXd weights;
2925 !atomic_environment_model_ && !active_posterior_) {
2926 if (auto kernel = mapSexpatMeanKernel(dof, weights)) {
2927 const auto dense = makeKernelMeanHessianMatrix(
2928 kernel, full_fit_observations_.R, weights);
2929 if (const auto done =
2930 finish_kernel_matrix(dense(position, hessian)))
2931 return *done;
2932 }
2933 }
2934 if (columns(prepareMeanHessian(R), hessian) && hessian.allFinite())
2935 return true;
2936 hessian.resize(0, 0);
2937 return false;
2938}
const Eigen::MatrixXd & secantQuadraticHessian() const
bool prepareMeanHessianVectorHssvd(const Coord &R, PreparedHssvdHessianVector &prepared) const
bool applyMeanHessianBlockHssvd(const PreparedHssvdHessianVector &prepared, const Eigen::MatrixXd &directions, Eigen::MatrixXd &hessian_block) const
MeanHessianAction prepareMeanHessian(const Coord &R)
Linear action of the physical posterior mean at one geometry.
int status
void addPriorHessianPairs(const std::vector< PriorHessianPair > &pairs, Eigen::MatrixXd &hessian)
Add the same pair blocks to a dense Cartesian Hessian.
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 Refus...

◆ calculateMeanHessianVectorDispatched()

bool gpr::GaussianProcessRegression::calculateMeanHessianVectorDispatched ( const Coord & R,
const Eigen::VectorXd & direction,
Eigen::VectorXd & hessian_vector )
nodiscard

Differentiate the physical posterior mean. The HS-SVD product is tried before the exact MAP preparation, which runs only when that product is unavailable. A prepared HS-SVD block that does not apply is a refusal, the same as the dense matrix, and is not replaced by the exact MAP kernel or the fourth-order Cartesian stencil. An exact MAP preparation that is empty or returns false is then a refusal and is not replaced by the stencil. A mean with no analytic contraction still uses the stencil.

Definition at line 3086 of file ActivePosterior.cpp.

3089{
3090 // calculatePotentialDispatched returns the random-feature mean on these
3091 // arms before any uncertainty-mode arm, so the Hessian takes this route
3092 // first; its Hessian is exact in the features and the descriptor.
3093 if (!atomic_environment_model_ && !active_posterior_ &&
3094 rff_model_.isBuilt() &&
3095 (rff_replaces_exact_ ||
3096 (uncertainty_mode_ == UncertaintyMode::LAPLACE_SLICE &&
3097 rff_features_ > 0))) {
3098 hessian_vector.resize(0);
3099 if (R.rows() != 1 || R.cols() != direction.size() || !R.allFinite() ||
3100 !direction.allFinite() || !sexpat_cov_func)
3101 return false;
3102 if (direction.norm() == 0.0) {
3103 hessian_vector = Eigen::VectorXd::Zero(direction.size());
3104 return true;
3105 }
3106 if (!rff_model_.meanHessianVector(R.row(0).transpose(), direction,
3107 hessian_vector))
3108 return false;
3109 if (rff_standardized_targets_ && std::isfinite(y_scale_) &&
3110 y_scale_ > 0.0)
3111 hessian_vector *= y_scale_;
3112 if (ffPriorMeanActive())
3113 hessian_vector += priors::applyPriorHessianPairs(
3114 ff_prior_mean_->hessianPairs(R.row(0)), direction);
3115 else if (zblPriorMeanActive())
3116 hessian_vector += priors::applyPriorHessianPairs(
3117 zbl_prior_mean_->hessianPairs(R.row(0)), direction);
3119 hessian_vector += secantQuadraticHessian() * direction;
3120 return hessian_vector.allFinite();
3121 }
3122 // Laplace, SVGD, and BMA predictive means are factor mixtures, including
3123 // when an HSSVD factor of the MAP mean is also available. A mixture that
3124 // refuses is not replaced by the stencil below.
3125 if (!atomic_environment_model_ && !active_posterior_ &&
3126 (uncertainty_mode_ == UncertaintyMode::LAPLACE ||
3127 uncertainty_mode_ == UncertaintyMode::SVGD ||
3128 uncertainty_mode_ == UncertaintyMode::BMA)) {
3129 const auto mixture = uncertainty_mode_ == UncertaintyMode::LAPLACE
3131 R, direction, hessian_vector)
3132 : uncertainty_mode_ == UncertaintyMode::SVGD
3133 ? calculateSvgdMixtureMeanHessianVector(
3134 R, direction, hessian_vector)
3135 : calculateBmaMixtureMeanHessianVector(
3136 R, direction, hessian_vector);
3138 return hessian_vector.allFinite();
3139 if (mixture == MixtureMeanHessianStatus::Refused) return false;
3140 }
3141 if (!atomic_environment_model_ && !active_posterior_ &&
3142 !optimizer_state_->mean_hessian.map_kernel_overrides_hssvd) {
3143 switch (meanHessianProductHssvd(R, direction, hessian_vector)) {
3145 return true;
3147 hessian_vector.resize(0);
3148 return false;
3150 break;
3151 }
3152 }
3153 hessian_vector.resize(0);
3154 if (R.rows() != 1 || R.cols() != direction.size() || !R.allFinite() ||
3155 !direction.allFinite() ||
3156 (!atomic_environment_model_ && !sexpat_cov_func))
3157 return false;
3158 if (atomic_environment_model_ && !atomicEnvironmentPosteriorBuilt())
3159 return false;
3160 // Build the exact MAP kernel action only when the spectral or prepared
3161 // descriptor contraction did not already consume the call.
3162 if (!atomic_environment_model_ && !active_posterior_) {
3163 Eigen::VectorXd weights;
3164 if (auto kernel = mapSexpatMeanKernel(direction.size(), weights)) {
3165 bool all_exact = false;
3166 bool has_exact_or_refusal = false;
3167 auto prepare = makeRefusalAwareKernelMeanHessian(
3168 kernel, full_fit_observations_.R, weights, &all_exact,
3169 &has_exact_or_refusal);
3170 if (all_exact || has_exact_or_refusal) {
3171 ++optimizer_state_->mean_hessian.dispatched_map_hessian_actions;
3172 bool exact_refusal = false;
3173 const auto action =
3174 prepare ? prepare(R.row(0).transpose(), exact_refusal)
3176 const bool ok =
3177 action &&
3178 action(direction, hessian_vector, exact_refusal) &&
3179 hessian_vector.size() == direction.size() &&
3180 hessian_vector.allFinite();
3181 if (!ok) {
3182 if (all_exact || exact_refusal) {
3183 hessian_vector.resize(0);
3184 return false;
3185 }
3186 hessian_vector.resize(0);
3187 } else {
3188 if (ffPriorMeanActive())
3189 hessian_vector += priors::applyPriorHessianPairs(
3190 ff_prior_mean_->hessianPairs(R.row(0)), direction);
3191 else if (zblPriorMeanActive())
3192 hessian_vector += priors::applyPriorHessianPairs(
3193 zbl_prior_mean_->hessianPairs(R.row(0)), direction);
3195 hessian_vector += secantQuadraticHessian() * direction;
3196 if (!hessian_vector.allFinite()) {
3197 hessian_vector.resize(0);
3198 return false;
3199 }
3200 return true;
3201 }
3202 }
3203 }
3204 }
3205 const double norm = direction.norm();
3206 if (!std::isfinite(norm)) return false;
3207 if (norm == 0.0) {
3208 hessian_vector = Eigen::VectorXd::Zero(direction.size());
3209 return true;
3210 }
3211 if (!atomic_environment_model_ && !active_posterior_ &&
3212 !optimizer_state_->mean_hessian.map_kernel &&
3214 uncertainty_mode_ == UncertaintyMode::MAP &&
3215 (sexpat_cov_func->usesManifoldChart() ||
3216 sexpat_cov_func->usesGeodesicHeatKernel()) &&
3217 R_matrix.rows() == a.size() && R_matrix.cols() >= R.cols() &&
3218 a.size() > 0 && a.size() % (R.cols() + 1) == 0) {
3219 const Eigen::Index count = a.size() / (R.cols() + 1);
3220 const Coord training = R_matrix.topRows(count).leftCols(R.cols());
3221 const Eigen::VectorXd weights = y_scale_ * unpermuteTrainingVector(a);
3222 if (!sexpat_cov_func->meanHessianVector(training, weights,
3223 R.row(0).transpose(), direction,
3224 hessian_vector))
3225 return false;
3226 if (ffPriorMeanActive())
3227 hessian_vector += priors::applyPriorHessianPairs(
3228 ff_prior_mean_->hessianPairs(R.row(0)), direction);
3229 else if (zblPriorMeanActive())
3230 hessian_vector += priors::applyPriorHessianPairs(
3231 zbl_prior_mean_->hessianPairs(R.row(0)), direction);
3233 hessian_vector += secantQuadraticHessian() * direction;
3234 return hessian_vector.allFinite();
3235 }
3236 if (!atomic_environment_model_ && active_posterior_ &&
3237 active_posterior_->mean_weights.size() > 0) {
3238 requireActivePosteriorBackground();
3239 resolveResidualHessianProbe(*active_posterior_);
3240 if (active_posterior_->residualCurvatureRefused()) {
3241 hessian_vector.resize(0);
3242 return false;
3243 }
3244 const auto& state = *active_posterior_;
3245 bool exact_refusal = false;
3246 const auto residual_action =
3247 state.residual_hessian_refusal
3248 ? state.residual_hessian_refusal(R.row(0).transpose(),
3249 exact_refusal)
3251 const auto background_action =
3252 state.background_hessian_refusal
3253 ? state.background_hessian_refusal(R.row(0).transpose(),
3254 exact_refusal)
3256 const bool background_exact = state.background_hessian_exact;
3257 const bool residual_exact =
3258 static_cast<bool>(state.kernel) && state.residual_hessian_exact;
3259 // A missing action from an exact term refuses the whole mean, even
3260 // when the other term is a generic stencil.
3261 if (exact_refusal || (background_exact && !background_action) ||
3262 (residual_exact && !residual_action)) {
3263 hessian_vector.resize(0);
3264 return false;
3265 }
3266 Eigen::VectorXd residual = Eigen::VectorXd::Zero(direction.size());
3267 const bool residual_ok =
3268 !state.kernel ||
3269 (residual_action &&
3270 residual_action(direction, residual, exact_refusal) &&
3271 residual.size() == direction.size());
3272 const bool background_ok =
3273 background_action &&
3274 background_action(direction, hessian_vector, exact_refusal) &&
3275 hessian_vector.size() == direction.size();
3276 if (residual_ok && background_ok) {
3277 hessian_vector += residual;
3278 if (ffPriorMeanActive())
3279 hessian_vector += priors::applyPriorHessianPairs(
3280 ff_prior_mean_->hessianPairs(R.row(0)), direction);
3281 else if (zblPriorMeanActive())
3282 hessian_vector += priors::applyPriorHessianPairs(
3283 zbl_prior_mean_->hessianPairs(R.row(0)), direction);
3285 hessian_vector += secantQuadraticHessian() * direction;
3286 if (hessian_vector.allFinite()) return true;
3287 }
3288 // An exact term that misses or returns false refuses the composed
3289 // mean. A generic partner that misses does not: the stencil below
3290 // still serves a mean with no exact term in the failure.
3291 if (exact_refusal || (background_exact && !background_ok) ||
3292 (residual_exact && !residual_ok) ||
3293 ((background_exact || residual_exact) && residual_ok &&
3294 background_ok)) {
3295 hessian_vector.resize(0);
3296 return false;
3297 }
3298 }
3299 const Eigen::VectorXd unit = direction / norm;
3300 double inverse_step_scale = 0.0;
3301 if (atomic_environment_model_) {
3302 inverse_step_scale =
3303 atomic_environment_posterior_->inverseCartesianLengthScale(
3304 R.row(0).transpose());
3305 } else {
3306 Eigen::VectorXd features, rate, gradient_norms;
3307 std::vector<int> types;
3309 R, atoms_config, unit, features, rate, types, &gradient_norms);
3310 const auto& lengths = sexpat_cov_func->getLengthScaleRef();
3311 // A tangent direction can have zero descriptor rate and finite
3312 // curvature. Full Cartesian gradient norms keep its stencil on the
3313 // molecular scale.
3314 for (Eigen::Index i = 0; i < rate.size(); ++i) {
3315 const Eigen::Index type = lengths.size() == 1 ? 0 : types[i];
3316 if (type >= lengths.size() || !(lengths.data()[type] > 0.0))
3317 return false;
3318 inverse_step_scale = std::max(
3319 inverse_step_scale, gradient_norms(i) / lengths.data()[type]);
3320 if (features(i) > 0.0)
3321 inverse_step_scale = std::max(inverse_step_scale,
3322 gradient_norms(i) / features(i));
3323 if (active_posterior_ &&
3324 type < active_posterior_->fitted_lengths.size())
3325 inverse_step_scale =
3326 std::max(inverse_step_scale,
3327 gradient_norms(i) /
3328 active_posterior_->fitted_lengths(type));
3329 }
3330 if (active_posterior_ && active_posterior_->environment_kernel)
3331 inverse_step_scale = std::max(
3332 inverse_step_scale,
3333 active_posterior_->environment_kernel->directionalInverseLength(
3334 R.row(0).transpose(), unit));
3335 if (active_posterior_ && active_posterior_->cartesian_kernel) {
3336 const auto& kernel = *active_posterior_->cartesian_kernel;
3337 inverse_step_scale = std::max(
3338 inverse_step_scale,
3339 (kernel.chart().jacobian(R.row(0).transpose()) * unit).norm() /
3340 kernel.lengthScale());
3341 }
3342 }
3343 if (!std::isfinite(inverse_step_scale)) return false;
3344 // Laplace, SVGD, and BMA already returned above, including a failed
3345 // mixture whose MAP mean has a pair-kernel product. What remains is a
3346 // mean with no analytic Hessian: an active-posterior residual, an
3347 // atomic environment, or a gradient-only arc model.
3348 const double step = std::pow(std::numeric_limits<double>::epsilon(), 0.2) /
3349 (inverse_step_scale > 0.0 ? inverse_step_scale : 1.0);
3350 Observation stencil;
3351 stencil.R.resize(4, R.cols());
3352 constexpr double shifts[] = {-2.0, -1.0, 1.0, 2.0};
3353 for (Eigen::Index i = 0; i < 4; ++i)
3354 stencil.R.row(i) = R.row(0) + shifts[i] * step * unit.transpose();
3356 if (stencil.G.rows() != 4 || stencil.G.cols() != R.cols() ||
3357 !stencil.G.allFinite())
3358 return false;
3359 hessian_vector =
3360 (norm / (12.0 * step)) * (8.0 * (stencil.G.row(2) - stencil.G.row(1)) -
3361 (stencil.G.row(3) - stencil.G.row(0)))
3362 .transpose();
3363 return hessian_vector.allFinite();
3364}
void calculatePotentialDispatched(Observation &image1)
Definition Predict.cpp:982
MixtureMeanHessianStatus calculateLaplaceMixtureMeanHessianVector(const Coord &R, const Eigen::VectorXd &direction, Eigen::VectorXd &hessian_vector)
static void computeDirectionalFeatures(const Coord &x, const AtomsConfiguration &conf_info, const Eigen::VectorXd &direction, Eigen::VectorXd &phi, Eigen::VectorXd &rates, std::vector< int > &pairtypes)
UncertaintyMode
Definition Structures.h:177

◆ calculateMeanHessianVectorHssvd()

bool gpr::GaussianProcessRegression::calculateMeanHessianVectorHssvd ( const Coord & R,
const Eigen::VectorXd & direction,
Eigen::VectorXd & hessian_vector ) const
nodiscard

Definition at line 1306 of file Decompose.cpp.

1309{
1310 return meanHessianProductHssvd(R, direction, hessian_vector) ==
1312}

◆ calculateMeanPrediction()

void gpr::GaussianProcessRegression::calculateMeanPrediction ( const Eigen::VectorXd & y)
protected

Posterior mean prediction w.r.t energy. This function mimics the following step from the MATLAB code: b = L[E_all;G_all(:)];.

Definition at line 688 of file Predict.cpp.

690{
691#ifdef GPR_LINALG_KOKKOS
692 if (hasDevicePosterior()) {
695 a.resize(0);
696 recordHyperparameterDataTerm(static_cast<double>(y.size()),
697 device_posterior_->objectiveParts()[1]);
698 return;
699 }
700#endif
701 // This function mimics the following MATLAB code
702 // b = L\‍[E_all;G_all(:)];
703 const Eigen::VectorXd y_perm = permuteTrainingVector(y);
704 if (rigid_deflation_.isActiveForFullOrder(y_perm.size())) {
705 rigid_deflation_.updateTargetStats(y_perm);
706 b = trainingSolver().whiten(rigid_deflation_.projectVector(y_perm));
707 } else {
708 b = trainingSolver().whiten(y_perm);
709 }
710 recordHyperparameterDataTerm(static_cast<double>(y.size()), b.dot(b));
711}
virtual void recordHyperparameterDataTerm(double, double)
std::shared_ptr< linalg::KokkosMolecularPosterior > device_posterior_
Eigen::VectorXd whiten(const Eigen::VectorXd &y) const

◆ calculateObservationForceVarianceReduction()

std::optional< JointObservationVarianceReduction > gpr::GaussianProcessRegression::calculateObservationForceVarianceReduction ( const EigenMatrix & positions,
Eigen::Index candidate_query,
const std::vector< Eigen::Index > & target_queries,
double noise_variance,
bool allow_hssvd_local = true )
nodiscard

Force-variance reduction from a complete energy-gradient query. Active residuals evaluate one target geometry at a time, preserving the full posterior and the background's joint query subset.

Definition at line 3462 of file ActivePosterior.cpp.

3466{
3467 const Eigen::Index count = positions.rows();
3468 const Eigen::Index dimensions = positions.cols();
3469 const Eigen::Index channels = dimensions + 1;
3470 if (count <= 0 || dimensions <= 0 || candidate_query < 0 ||
3471 candidate_query >= count || target_queries.empty() ||
3472 !positions.allFinite() || !std::isfinite(noise_variance) ||
3473 noise_variance < 0.0)
3474 return std::nullopt;
3475 std::vector<bool> seen(static_cast<std::size_t>(count), false);
3476 for (const Eigen::Index target: target_queries) {
3477 if (target < 0 || target >= count || seen[target]) return std::nullopt;
3478 seen[target] = true;
3479 }
3480 if (!active_posterior_ || !active_posterior_->kernel ||
3481 detail::matrixExactlyEqual(positions,
3482 active_posterior_->observations.R)) {
3483 EigenMatrix covariance;
3484 calculateObservationPosteriorCovariance(positions, covariance,
3485 allow_hssvd_local);
3487 covariance, count, dimensions, candidate_query, target_queries,
3488 noise_variance);
3489 }
3490
3491 requireActivePosteriorBackground();
3492 const auto& state = *active_posterior_;
3493 const VarianceSubsetScope subset(variance_subset_configurations_,
3494 variance_subset_forced_ids_,
3495 state.background_subset_ids);
3496 if (dimensions != state.observations.R.cols())
3497 throw std::invalid_argument("invalid active posterior query geometry");
3498 EigenMatrix background, whitened;
3499 calculateBackgroundObservationPosteriorCovariance(positions, background,
3500 false);
3501 {
3502 EigenMatrix cross;
3504 positions, state.observations.R, cross);
3505 cross += state.residual_cross(positions);
3506 whitened = state.posterior.whitenPredictionCrossCovariance(cross);
3507 }
3508 if (!background.allFinite()) return std::nullopt;
3509
3510 const Coord candidate_position = positions.middleRows(candidate_query, 1);
3511 EigenMatrix candidate =
3512 state.kernel->jointEnergyGradientCovariance(candidate_position);
3513 EigenMatrix candidate_whitened(whitened.rows(), channels);
3514 for (Eigen::Index channel = 0; channel < channels; ++channel)
3515 candidate_whitened.col(channel) =
3516 whitened.col(channel * count + candidate_query);
3517 candidate.noalias() -= candidate_whitened.transpose() * candidate_whitened;
3518 for (Eigen::Index row = 0; row < channels; ++row)
3519 for (Eigen::Index column = 0; column < channels; ++column)
3520 candidate(row, column) +=
3521 background(row * count + candidate_query,
3522 column * count + candidate_query);
3523
3524 // The same candidate precision weights serve every reference geometry.
3525 // Residual self blocks contribute only their force diagonal to the trace.
3526 const auto candidate_cross =
3527 makeKernelCrossCovariance(state.kernel, candidate_position);
3528 EigenMatrix target_candidate(target_queries.size() * dimensions, channels);
3529 double target_variance = 0.0;
3530 linalg::ExactSum stable_target_variance;
3531 linalg::ExactSum stable_target_signal;
3532 Eigen::Index first = 0;
3533 for (const Eigen::Index target: target_queries) {
3534 const Coord target_position = positions.middleRows(target, 1);
3535 const EigenMatrix residual_self =
3536 state.kernel->jointEnergyGradientCovariance(target_position);
3537 target_candidate.middleRows(first, dimensions) =
3538 candidate_cross(target_position).bottomRows(dimensions);
3539 for (Eigen::Index channel = 1; channel < channels; ++channel) {
3540 const Eigen::Index source = channel * count + target;
3542 stable_target_variance.add(background(source, source));
3543 stable_target_variance.add(residual_self(channel, channel));
3544 stable_target_signal.add(background(source, source));
3545 stable_target_signal.add(residual_self(channel, channel));
3546 for (Eigen::Index row = 0; row < whitened.rows(); ++row)
3547 stable_target_variance.addProduct(-whitened(row, source),
3548 whitened(row, source));
3549 } else {
3550 target_variance += background(source, source) +
3551 residual_self(channel, channel) -
3552 whitened.col(source).squaredNorm();
3553 }
3554 target_candidate.row(first + channel - 1).noalias() -=
3555 whitened.col(source).transpose() * candidate_whitened;
3556 for (Eigen::Index column = 0; column < channels; ++column)
3557 target_candidate(first + channel - 1, column) +=
3558 background(source, column * count + candidate_query);
3559 }
3560 first += dimensions;
3561 }
3563 target_variance = stable_target_variance.value();
3564 // The reduction subtracts squares of the active posterior's solve, so
3565 // the allowance is that factor's, asked for only if the value is
3566 // negative.
3568 target_variance, stable_target_signal.value(),
3569 target_variance < 0.0 ? state.posterior.schurRelativeError()
3570 : 0.0))
3571 return std::nullopt;
3572 }
3573 return jointObservationVarianceReduction(std::move(candidate),
3574 target_candidate, target_variance,
3575 noise_variance);
3576}
void calculateBackgroundObservationPosteriorCrossCovariance(const EigenMatrix &left, const EigenMatrix &right, EigenMatrix &covariance, const Eigen::VectorXd *mean_weights=nullptr)
Definition Variance.cpp:906
void calculateObservationPosteriorCovariance(const EigenMatrix &positions, EigenMatrix &K_post, bool allow_hssvd_local=true)
bool acceptStablePosteriorVariance(double &variance, double signal_variance, double relative_allowance) noexcept
Accept one stable posterior variance.
Definition ExactSchur.h:86
KernelOperator::CrossCovarianceFunction makeKernelCrossCovariance(std::shared_ptr< const KernelOperator > kernel, const Eigen::MatrixXd &training)
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 > jointObservationForceVarianceReduction(const Eigen::MatrixXd &posterior_covariance, const Eigen::Index query_count, const Eigen::Index dimensions, const Eigen::Index candidate_query, const std::vector< Eigen::Index > &target_queries, const double noise_variance)
Integrated force-variance reduction from one joint energy-force query.

◆ calculateObservationFunctionalVariance()

double gpr::GaussianProcessRegression::calculateObservationFunctionalVariance ( const EigenMatrix & positions,
const Eigen::VectorXd & weights )
nodiscard

Latent variance of a linear energy-gradient observation in physical units. Weights use the joint channel order above. A configured variance subset matches the joint covariance; otherwise contraction precedes the global posterior solve. Reporting noise and calibration are absent.

Definition at line 1100 of file Variance.cpp.

1102{
1103 if (positions.cols() <= 0 || !positions.allFinite() ||
1104 weights.size() != positions.rows() * (positions.cols() + 1) ||
1105 !weights.allFinite())
1106 throw std::invalid_argument("invalid posterior observation functional");
1107 if (positions.rows() == 0) return 0.0;
1108 (void)checkedOutputVarianceScaleSquared();
1109 if (atomic_environment_model_)
1110 return calculateAtomicEnvironmentFunctionalVariance(positions, weights);
1111 if (active_posterior_)
1112 return calculateActivePosteriorFunctionalVariance(positions, weights);
1113 EigenMatrix integrated;
1114 if (calculateLaplaceObservationCovariance(positions, integrated, &weights))
1115 return integrated(0, 0);
1116 return calculateBackgroundObservationFunctionalVariance(positions, weights);
1117}

◆ calculateObservationNoiseDiagonal()

Eigen::VectorXd gpr::GaussianProcessRegression::calculateObservationNoiseDiagonal ( const EigenMatrix & positions) const
nodiscard

Physical Gaussian measurement variance, including jitter, in the joint energy-gradient channel order used for sequential conditioning.

Definition at line 550 of file Variance.cpp.

552{
553 if (positions.rows() == 0) return Eigen::VectorXd(0);
554 if (!lik_gaussian || positions.cols() == 0 || !positions.allFinite())
555 throw std::invalid_argument(
556 "Finite Gaussian observation sites required");
557 EigenMatrix rows;
558 Eigen::VectorXd indices;
559 aux::AuxiliaryFunctionality{}.assembleMatrixOfRepetitiveCoordinates(
560 positions, rows, indices);
561 Eigen::VectorXd noise = likelihoodDiagonal(rows);
562 noise.array() += jitter_sigma2;
563 noise *= checkedOutputVarianceScaleSquared();
564 if (!noise.allFinite() || (noise.array() < 0).any())
565 throw std::runtime_error("Gaussian observation noise is invalid");
566 return noise;
567}

◆ calculateObservationPosteriorCovariance()

void gpr::GaussianProcessRegression::calculateObservationPosteriorCovariance ( const EigenMatrix & positions,
EigenMatrix & K_post,
bool allow_hssvd_local = true )

Compute the latent joint posterior covariance of energy and gradient channels at query positions in physical output units. Channel order matches Observation: energies for every query, followed by each gradient column.

Definition at line 1082 of file Variance.cpp.

1085{
1086 (void)checkedOutputVarianceScaleSquared();
1087 if (atomic_environment_model_) {
1088 calculateAtomicEnvironmentCovariance(positions, K_post);
1089 return;
1090 }
1091 if (active_posterior_) {
1092 calculateActivePosteriorCovariance(positions, K_post);
1093 return;
1094 }
1095 if (calculateLaplaceObservationCovariance(positions, K_post)) return;
1096 calculateBackgroundObservationPosteriorCovariance(positions, K_post,
1097 allow_hssvd_local);
1098}

◆ calculatePosteriorMeanPrediction() [1/2]

void gpr::GaussianProcessRegression::calculatePosteriorMeanPrediction ( )
protected

Calculate posterior mean prediction w.r.t energy. This function mimics the following step from the MATLAB code: a = L'(L[E_all;G_all(:)]);.

Definition at line 153 of file Predict.cpp.

154{
155#ifdef GPR_LINALG_KOKKOS
156 if (hasDevicePosterior()) return;
157#endif
158 // This function mimics the following MATLAB code
159 // a = L'\‍(L\‍[E_all;G_all(:)]);
161 if (rigid_deflation_.isActiveForFullOrder(R_matrix.rows()) &&
162 a.size() == rigid_deflation_.deflated_rows) {
163 a = rigid_deflation_.liftVectorZeroRigid(a);
164 }
165}

◆ calculatePosteriorMeanPrediction() [2/2]

void gpr::GaussianProcessRegression::calculatePosteriorMeanPrediction ( const Eigen::VectorXd & y)
protected

Definition at line 167 of file Predict.cpp.

169{
170#ifdef GPR_LINALG_KOKKOS
171 if (hasDevicePosterior()) {
174 a.resize(0);
175 recordHyperparameterDataTerm(static_cast<double>(y.size()),
176 device_posterior_->objectiveParts()[1]);
177 return;
178 }
179#endif
180 if (use_precision_) {
181 const EigenMatrix precision = trainingSolver().inverse();
182 const Eigen::VectorXd y_perm = permuteTrainingVector(y);
183 if (rigid_deflation_.isActiveForFullOrder(y_perm.size())) {
184 rigid_deflation_.updateTargetStats(y_perm);
185 a = rigid_deflation_.liftVectorZeroRigid(
186 precision * rigid_deflation_.projectVector(y_perm));
187 } else {
188 a.noalias() = precision * y_perm;
189 }
190 } else {
192 }
193}
void calculatePosteriorMeanPrediction()
Calculate posterior mean prediction w.r.t energy. This function mimics the following step from the MA...
Definition Predict.cpp:153

◆ calculatePotential()

void gpr::GaussianProcessRegression::calculatePotential ( Observation & image1)

Calculate potential within GPR model.

This auxiliary function calculates energy and gradient predictions for given images R according to a GPR model.

Parameters
image1Observation at image 1

Definition at line 713 of file Predict.cpp.

714{
715#ifdef GPR_LINALG_KOKKOS
716 if (predictDevicePosterior(image1, false)) return;
717#endif
718 if (atomic_environment_model_) {
719 calculateAtomicEnvironmentPotential(image1);
720 return;
721 }
722 // NOTE: C is a truncated covariance!
723
724 Index_t N_im = image1.R.rows();
725 Index_t D = image1.R.cols();
726 EigenMatrix R_mod;
727 Eigen::VectorXd R_mod_ind;
728 EigenMatrix KK;
729 Eigen::VectorXd EG_R;
730 aux::AuxiliaryFunctionality aux_func;
731
732 // [repmat(R,D+1,1),reshape(repmat(0:D,N_im,1),[],1)]
733 aux_func.assembleMatrixOfRepetitiveCoordinates(image1.R, R_mod, R_mod_ind);
734
735 // When the most recent Cholesky rescue in decomposeCovarianceMatrix fails,
736 // `a` can retain a size from a differently-sized training set. Emit NaN
737 // for energy/gradient so the caller's existing "Energy is not finite"
738 // path handles the failure cleanly; the path is wired into the SCG/dimer
739 // outer loops as a retry signal. Same NaN-fallback when the model has no
740 // training data.
741 // at all (R_matrix empty): the per-tile cross-cov assembly downstream
742 // would otherwise dereference weights[0] on a zero-size alpha.
743 if (R_matrix.rows() == 0 || a.size() == 0 || R_matrix.rows() != a.size()) {
744 const double nan = std::numeric_limits<double>::quiet_NaN();
745 image1.E.resize(1, N_im);
746 image1.G.resize(N_im, D);
747 for (Index_t i = 0; i < N_im; ++i)
748 image1.E(0, i) = nan;
749 for (Index_t i = 0; i < N_im; ++i)
750 for (Index_t j = 0; j < D; ++j)
751 image1.G(i, j) = nan;
752 ++num_of_potential_calls;
753 return;
754 }
755
756 // HS-SVD cancellation-free force path: predict energy + Cartesian forces
757 // from the stable basis (predictEnergy/Gradient on the reduced coeff p),
758 // never forming the ill-conditioned alpha = K^{-1} y. This is what makes
759 // the HS-SVD path numerically robust WITHOUT output normalization. Gated
760 // behind the backend (off by default; production path unchanged).
761 if (use_hssvd_backend_ && hssvd_basis_valid_ &&
762 hssvd_basis_.numObs() == energy_and_gradient.size() &&
763 hssvd_p_.size() > 0 && hssvd_mean_feat_.size() > 0) {
764 predictPotentialHssvd(image1);
765 return;
766 }
767 if (descriptor_predictor_ready_ && !use_hssvd_backend_ &&
768 hssvd_dual_predict_weights_.size() == R_matrix.rows() &&
769 hssvd_train_qtil_.rows() > 0) {
770 predictPotentialHssvdDual(image1);
771 return;
772 }
773
774#ifdef GPR_LINALG_SCALAPACK
775 Eigen::VectorXd a_unpermuted =
778 : a;
779 // Conditioning symptom on the live force path: alpha = K^{-1} y. With
780 // O(1-10) eV / (eV/A) targets, max|alpha| >> ~1e2 means K^{-1} is
781 // amplifying (ill-conditioned), so mu = sum alpha_i k_i cancels large
782 // terms and 1 ULP anywhere blows up. Defined in EnergyGradient.cpp.
783 if (a_unpermuted.size() > 0) {
784 const double amax = a_unpermuted.cwiseAbs().maxCoeff();
785 if (amax > g_max_abs_alpha) g_max_abs_alpha = amax;
786 }
787 Eigen::VectorXd EG_R_local = Eigen::VectorXd::Zero(R_mod.rows());
788 Eigen::VectorXd uDdim, uDdim2;
790 extractUniqueIndices(R_mod_ind, uDdim2);
791
792 auto& _pp = predict_profile();
793 if (profile_predict_mean_) {
794 _pp.enabled.store(true, std::memory_order_relaxed);
795 }
796 const auto _t0 = std::chrono::steady_clock::now();
798 R_matrix, R_mod, R_indices, uDdim, R_mod_ind, uDdim2, *const_cov_fun,
799 a_unpermuted, EG_R_local, training_cholesky_is_distributed_, true);
800 const auto _t1 = std::chrono::steady_clock::now();
801 {
802 // Alpha-K Path 2 (Schmitz/Chmiela JPCL 2022 eq.6):
803 // per-test-point per-pair predict-mean, bypassing the
804 // (D_train x D_test) accumulator sub-block loop.
805 if (use_alpha_k_predict_mean_ && sexpat_cov_func &&
806 full_cartesian_training_dimension_ == D &&
807 !sexpat_cov_func->usesManifoldChart() &&
808 !sexpat_cov_func->usesGeodesicHeatKernel()) {
809 // R_matrix is the per-observation training matrix with each
810 // training POSITION repeated (D + 1) times (one row per
811 // energy + per gradient component). Extract the unique
812 // training positions for the alpha-K predict: the first
813 // num_train_pts rows (the energy-observation slab; matches
814 // extractCoordinatesByIndex(x, ind, 0, x_loc_0)).
815 const Eigen::Index num_train_pts = R_matrix.rows() / (D + 1);
816 // a_unpermuted layout: [alpha_E (num_train_pts entries),
817 // alpha_G for d=1 (num_train_pts), ..., alpha_G for d=D
818 // (num_train_pts)]. predictMeanAlphaK indexes
819 // alpha_G_flat[d * num_train + i] -- the SAME layout.
820
821 Eigen::VectorXd alpha_k_mean = Eigen::VectorXd::Zero(R_mod.rows());
822 Eigen::VectorXd mu_E_out = Eigen::VectorXd::Zero(N_im);
823 Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic,
824 Eigen::RowMajor>
825 mu_G_out = Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic,
826 Eigen::RowMajor>::Zero(N_im, D);
827 const auto predict_full_training_set = [&]() {
828 sexpat_cov_func->predictMeanAlphaK(
829 R_matrix.topRows(num_train_pts), image1.R,
830 a_unpermuted.head(num_train_pts), a_unpermuted, mu_E_out,
831 mu_G_out);
832 };
833
834 // The training points are contracted in chunks of a fixed size
835 // that does not depend on the rank count. A chunk is evaluated
836 // whole on one rank, so its partial means are a function of its
837 // contents alone, and the chunk partials enter exact accumulators
838 // whose merge is an integer sum. The reduced mean therefore
839 // carries the same bits at every rank count, at one rank as well,
840 // which contracts every chunk itself. A training set of one chunk
841 // is the full contraction.
842 constexpr Eigen::Index kAlphaKChunk = 64;
843 const Eigen::Index chunks =
844 (num_train_pts + kAlphaKChunk - 1) / kAlphaKChunk;
845 if (chunks <= 1) {
846 predict_full_training_set();
847 } else {
848 int mpi_np = 1, mpi_rank = 0;
849 if (training_cholesky_is_distributed_) {
850 auto& alpha_st = backend().distributed();
851 alpha_st.initialize();
852 mpi_np = alpha_st.nprocs();
853 mpi_rank = alpha_st.myrank();
854 }
855 std::vector<linalg::ExactSum> mean_E(
856 static_cast<std::size_t>(N_im));
857 std::vector<linalg::ExactSum> mean_G(
858 static_cast<std::size_t>(N_im * D));
859 Eigen::VectorXd mu_E_chunk(N_im);
860 Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic,
861 Eigen::RowMajor>
862 mu_G_chunk(N_im, D);
863 Eigen::VectorXd alpha_G_flat_slice;
864 for (Eigen::Index chunk = mpi_rank; chunk < chunks;
865 chunk += mpi_np) {
866 const Eigen::Index slice_start = chunk * kAlphaKChunk;
867 const Eigen::Index slice_count = std::min<Eigen::Index>(
868 kAlphaKChunk, num_train_pts - slice_start);
869 const EigenMatrix x_train_slice =
870 R_matrix.middleRows(slice_start, slice_count);
871 const Eigen::VectorXd alpha_E_slice =
872 a_unpermuted.segment(slice_start, slice_count);
873 // Re-pack alpha_G_flat for the train-slice layout
874 // predictMeanAlphaK expects: entry
875 // [d * slice_count + i] = full alpha
876 // [d * num_train_full + (slice_start + i)].
877 alpha_G_flat_slice.resize(slice_count * (D + 1));
878 for (Eigen::Index d = 0; d <= D; ++d) {
879 alpha_G_flat_slice.segment(d * slice_count,
880 slice_count) =
881 a_unpermuted.segment(
882 d * num_train_pts + slice_start, slice_count);
883 }
884 mu_E_chunk.setZero();
885 mu_G_chunk.setZero();
886 sexpat_cov_func->predictMeanAlphaK(
887 x_train_slice, image1.R, alpha_E_slice,
888 alpha_G_flat_slice, mu_E_chunk, mu_G_chunk);
889 for (Eigen::Index m = 0; m < N_im; ++m) {
890 mean_E[static_cast<std::size_t>(m)].add(mu_E_chunk(m));
891 for (Eigen::Index d = 0; d < D; ++d)
892 mean_G[static_cast<std::size_t>(m * D + d)].add(
893 mu_G_chunk(m, d));
894 }
895 }
896 if (mpi_np > 1) {
897 backend().exact_sum_bcast(mean_E.data(),
898 static_cast<int>(mean_E.size()));
899 backend().exact_sum_bcast(mean_G.data(),
900 static_cast<int>(mean_G.size()));
901 }
902 for (Eigen::Index m = 0; m < N_im; ++m) {
903 mu_E_out(m) = mean_E[static_cast<std::size_t>(m)].value();
904 for (Eigen::Index d = 0; d < D; ++d)
905 mu_G_out(m, d) =
906 mean_G[static_cast<std::size_t>(m * D + d)].value();
907 }
908 }
909
910 // Splice mu_E + mu_G into alpha_k_mean using the column-major
911 // (m, d) layout matching image1.E / image1.G downstream.
912 for (Index_t m = 0; m < N_im; ++m) {
913 alpha_k_mean(m) += mu_E_out(m);
914 }
915 for (Index_t d = 0; d < D; ++d) {
916 for (Index_t m = 0; m < N_im; ++m) {
917 alpha_k_mean(N_im + d * N_im + m) += mu_G_out(m, d);
918 }
919 }
920 EG_R_local += alpha_k_mean;
921 } else {
922 Eigen::VectorXd tmp = Eigen::VectorXd::Zero(R_mod.rows());
924 R_matrix, R_mod, R_indices, uDdim, R_mod_ind, uDdim2,
925 *sexpat_cov_func, a_unpermuted, tmp,
926 training_cholesky_is_distributed_, true);
927 EG_R_local += tmp;
928 }
929 }
930 const auto _t2 = std::chrono::steady_clock::now();
931 if (profile_predict_mean_) {
932 const auto to_ns = [](auto a, auto b) {
933 return std::chrono::duration_cast<std::chrono::nanoseconds>(b - a)
934 .count();
935 };
936 _pp.nanos_const.fetch_add(to_ns(_t0, _t1), std::memory_order_relaxed);
937 _pp.nanos_sexpat.fetch_add(to_ns(_t1, _t2), std::memory_order_relaxed);
938 _pp.nanos_total.fetch_add(to_ns(_t0, _t2), std::memory_order_relaxed);
939 _pp.calls.fetch_add(1, std::memory_order_relaxed);
940 }
941
942 // accumulateCrossCovarianceMatVecLocal() already returns the assembled
943 // prediction vector on every rank. Reducing again here scales the final
944 // prediction by nprocs and breaks multi-rank correctness.
945 EG_R = EG_R_local;
946#else
947 // KK =
948 // gp_cov(gp,R_all2,[repmat(R,D+1,1),reshape(repmat(0:D,N_im,1),[],1)]);
949 evaluateCovarianceMatrix(R_matrix, R_mod, R_indices, R_mod_ind, KK);
950 KK = permuteTrainingRows(KK);
951
952 // EG_R = KK'*a. Compensated and the named modes share
953 // evaluateStoredProduct. Compensated mode sums each TwoProductFMA
954 // expansion with ExactSum and rounds once, so 2^54 + 1 - 2^54 stays 1
955 // and a residual below the running Neumaier correction is kept.
956 EG_R.resize(KK.cols());
957 const auto product_mode = linalg::productMode();
958 // Columns are the energy and the force components of each test point.
959 // contractPredictionMatrix runs those dots on the OpenMP team when the
960 // measured fork cost says the team is faster. Each dot keeps its own
961 // ascending index order.
962 linalg::contractPredictionMatrix(KK.data(), static_cast<int>(KK.rows()),
963 static_cast<int>(KK.cols()), a.data(),
964 EG_R.data(), product_mode);
965#endif
966
967 // E_R = EG_R(1:N_im,1);
968 image1.E.resize(1, N_im);
969 image1.E = Eigen::Map<const Eigen::RowVectorXd>(EG_R.data(), N_im);
970
971 // G_R = reshape(EG_R((N_im+1):end,1),N_im,D);
972 // EG_R stores gradient columns contiguously in column-major order, so we
973 // use a ColMajor map and assign to RowMajor G.
974 image1.G.resize(N_im, D);
975 image1.G = Eigen::Map<const Eigen::Matrix<double, Eigen::Dynamic,
976 Eigen::Dynamic, Eigen::ColMajor>>(
977 EG_R.data() + N_im, N_im, D);
978
979 ++num_of_potential_calls;
980}
bool predictDevicePosterior(Observation &image, bool variance)
void accumulateCrossCovarianceMatVecLocal(const EigenMatrix &x1, const EigenMatrix &x2, const Eigen::VectorXd &ind_Ddim, const Eigen::VectorXd &uDdim, const Eigen::VectorXd &ind_Ddim2, const Eigen::VectorXd &uDdim2, CovFunc &cov_func, const Eigen::VectorXd &weights, Eigen::VectorXd &output, bool do_reduce=true, bool select_prediction_product=false) const
Accumulate local K(x1, x2)^T * weights contributions without materializing the full cross-covariance ...
void contractPredictionMatrix(const double *column_major, int rows, int cols, const double *coefficients, double *output, ProductMode mode)
double g_max_abs_alpha

◆ calculatePotentialBatch()

void gpr::GaussianProcessRegression::calculatePotentialBatch ( std::vector< Observation * > queries)

One dispatched mean predict for B same-composition queries. Stacks the query rows, assembles one cross-covariance, writes each query's energy and gradient. Empty or mixed-D lists are a no-op. Sequential calculatePotentialDispatched on the same queries must match.

Definition at line 1132 of file Predict.cpp.

1134{
1135 Observation stacked;
1136 std::vector<Index_t> row_counts;
1137 if (!stackSameCompositionQueries(queries, stacked, row_counts)) return;
1139 unstackEnergyGradient(stacked, queries, row_counts);
1140}

◆ calculatePotentialBMA()

void gpr::GaussianProcessRegression::calculatePotentialBMA ( Observation & image1)

Bayesian Model Averaging gold-standard reference predict and variance. Marginalises the predictive distribution over a 2D log10 grid (lengthScale x noise_var) weighted by the posterior p(theta_k | D) ~ exp(-NLML(theta_k)). Routed via calculatePotentialDispatched / calculateVarianceDispatched when –uncertainty-mode=bma. The grid is fitted from scratch on each call (no cache); per-call cost is n_grid noiseless Cholesky decompositions, intentionally heavier than LAPLACE since BMA is the validation reference for the LAPLACE mixture.

Definition at line 121 of file BMA.cpp.

122{
123 BMAPrediction pred;
124 if (!runBMAGrid(image1, pred)) {
125 calculatePotential(image1);
126 return;
127 }
128 const Index_t N_im = static_cast<Index_t>(image1.R.rows());
129 const Index_t D = static_cast<Index_t>(image1.R.cols());
130 writeBMAOutput(pred.mean, N_im, D, image1);
131}
void calculatePotential(Observation &image1)
Calculate potential within GPR model.
Definition Predict.cpp:713

◆ calculatePotentialDispatched()

void gpr::GaussianProcessRegression::calculatePotentialDispatched ( Observation & image1)

Dispatched predict: routes to calculatePotential (MAP) or calculatePotentialLaplace based on uncertainty_mode_. This is what AtomicDimer / GPNEB should call; the explicit non-dispatched methods stay available for direct use (e.g. tests).

Definition at line 982 of file Predict.cpp.

984{
985 ScopedPredictTimer predict_timer;
986 if (atomic_environment_model_) {
987 calculateAtomicEnvironmentPotential(image1);
988 return;
989 }
990 if (active_posterior_) {
991 calculateActivePosteriorMean(image1);
992 return;
993 }
994 calculateBackgroundPotentialDispatched(image1);
995}

◆ calculatePotentialLaplace()

void gpr::GaussianProcessRegression::calculatePotentialLaplace ( Observation & image1)

Laplace-mixture-mean potential prediction (INLA, Rue et al. 2009).

Equivalent to calculatePotential in API – writes into image1.E and image1.G – but the predictive mean is the weighted-mixture mean over the CCD grid centred at the current MAP hyperparameters. The posterior factor state is keyed by the training-state stamp; query coordinates do not enter that stamp.

Falls back to the standard calculatePotential if any precondition fails (Hessian non-PD, directional oracle refuses, training data absent). Always safe to call.

Definition at line 1341 of file LaplaceSlice.cpp.

1342{
1343 if (!ensureLaplacePosterior()) {
1344 calculatePotential(image1);
1345 return;
1346 }
1347
1348 Observation mean_out = image1;
1349 if (!calculateLaplacePosteriorMoments(*laplace_posterior_, image1, mean_out,
1350 nullptr)) {
1351 calculatePotential(image1);
1352 return;
1353 }
1354 image1.E = mean_out.E;
1355 image1.G = mean_out.G;
1356 ++num_of_potential_calls;
1357}

◆ calculatePotentialLaplaceSlice()

void gpr::GaussianProcessRegression::calculatePotentialLaplaceSlice ( Observation & image1)

Slice-sampling Laplace marginalisation (UncertaintyMode:: LAPLACE_SLICE). Caches M = slice_laplace_opts_.n_samples posterior samples (theta_k, alpha_k = K(theta_k)^-1 y) on the first call after a training-data or theta_* change, then averages per-sample mean predictions across the cache. No new Cholesky on hot calls; per-call cost is O(M * n_train * n_query). Falls back to MAP if the slice burst fails (signature-invalid, NaN initial log-target, kernel state inconsistent). See Murray & Adams 2010 NIPS, arxiv 1006.0868.

Definition at line 752 of file LaplaceSlice.cpp.

754{
755 if (!runSliceLaplacePredict(image1, /*want_variance=*/false)) {
756 calculatePotential(image1);
757 return;
758 }
759 ++num_of_potential_calls;
760}

◆ calculatePotentialRFF()

void gpr::GaussianProcessRegression::calculatePotentialRFF ( Observation & image)

Definition at line 58 of file RFF.cpp.

59{
60 // Pass-through: RFFModel writes the predict mean (energy +
61 // gradient) into image1.E / image1.G via Bayesian linear
62 // regression in the random-feature space. Bumps the GP's call
63 // counter to keep diagnostic parity with the exact-GP predict.
64 rff_model_.calculatePotential(image1);
65 if (rff_standardized_targets_) rffUnstandardizePrediction(image1);
66 addPriorMeanToObservation(image1);
67 ++num_of_potential_calls;
68}

◆ calculatePotentialSVGD()

void gpr::GaussianProcessRegression::calculatePotentialSVGD ( Observation & image1)

SVGD particle posterior predict + variance. Routed via calculatePotentialDispatched / calculateVarianceDispatched when –uncertainty-mode=svgd.

Definition at line 87 of file SVGD.cpp.

88{
89 // The particle-fit oracle decomposes at other hyperparameters and
90 // leaves that factor behind. Curvature for the next mixture is the
91 // Hessian at the caller's theta, so rebuild that factor first.
92 if (R_matrix.rows() > 0 && R_indices.size() == R_matrix.rows())
94 // Predict using SVGD particles as a uniformly weighted mixture.
95 LaplaceINLA local_laplace;
96 if (!fitLaplaceFromScratch(local_laplace)) {
97 Observation mean_out = image1;
98 if (usesRankOwnedMixturePosterior() &&
99 calculateRankOwnedMapPosteriorMoments(image1, mean_out, nullptr)) {
100 image1.E = mean_out.E;
101 image1.G = mean_out.G;
102 ++num_of_potential_calls;
103 return;
104 }
105 calculatePotential(image1);
106 return;
107 }
108 laplace::SteinVariational local_svgd;
109 if (!fitSVGDFromScratch(local_laplace, local_svgd)) {
110 Observation mean_out = image1;
111 if (usesRankOwnedMixturePosterior() &&
112 calculateRankOwnedMapPosteriorMoments(image1, mean_out, nullptr)) {
113 image1.E = mean_out.E;
114 image1.G = mean_out.G;
115 ++num_of_potential_calls;
116 return;
117 }
118 calculatePotential(image1);
119 return;
120 }
121 const auto& particles = local_svgd.particles();
122 if (particles.empty() || R_matrix.size() == 0 ||
123 energy_and_gradient.size() == 0) {
124 Observation mean_out = image1;
125 if (usesRankOwnedMixturePosterior() &&
126 calculateRankOwnedMapPosteriorMoments(image1, mean_out, nullptr)) {
127 image1.E = mean_out.E;
128 image1.G = mean_out.G;
129 ++num_of_potential_calls;
130 return;
131 }
132 calculatePotential(image1);
133 return;
134 }
135 const LaplacePosteriorSignature signature =
136 currentLaplacePosteriorSignature();
138 if (!buildUniformParticlePosteriorState(particles, signature, state)) {
139 Observation mean_out = image1;
140 if (usesRankOwnedMixturePosterior() &&
141 calculateRankOwnedMapPosteriorMoments(image1, mean_out, nullptr)) {
142 image1.E = mean_out.E;
143 image1.G = mean_out.G;
144 ++num_of_potential_calls;
145 return;
146 }
147 calculatePotential(image1);
148 return;
149 }
150 Observation mean_out = image1;
151 if (!calculateLaplacePosteriorMoments(state, image1, mean_out, nullptr)) {
152 if (usesRankOwnedMixturePosterior() &&
153 calculateRankOwnedMapPosteriorMoments(image1, mean_out, nullptr)) {
154 image1.E = mean_out.E;
155 image1.G = mean_out.G;
156 ++num_of_potential_calls;
157 return;
158 }
159 calculatePotential(image1);
160 return;
161 }
162 image1.E = mean_out.E;
163 image1.G = mean_out.G;
164 ++num_of_potential_calls;
165}
bool decomposeForFittedTargets()
Factor the fitted design at the current hyperparameters and leave the posterior weights those of the ...

◆ calculateVariance()

void gpr::GaussianProcessRegression::calculateVariance ( Observation & image1)
virtual

Compute predictive variance for energy and gradient. Corresponds to MATLAB get_variance.m.

Reimplemented in gpr::StudentTProcessRegression.

Definition at line 353 of file Variance.cpp.

354{
355 ScopedVarianceTimer variance_timer;
356#ifdef GPR_LINALG_KOKKOS
357 if (predictDevicePosterior(image1, true)) return;
358#endif
359 if (atomic_environment_model_) {
360 calculateAtomicEnvironmentVariance(image1);
361 return;
362 }
363 if (canUseHssvdVariance()) {
365 return;
366 }
367 // NOTE: C is a truncated covariance!
368 Index_t n = image1.R.rows();
369 EigenMatrix R_mod;
370 Eigen::VectorXd R_mod_ind;
371 EigenMatrix KK;
372 Eigen::VectorXd V;
373 Eigen::VectorXd VarEG_R;
374 aux::AuxiliaryFunctionality aux_func;
375
376 // R2 = [repmat(R,D+1,1),reshape(repmat(0:D,n,1),[],1)];
377 aux_func.assembleMatrixOfRepetitiveCoordinates(image1.R, R_mod, R_mod_ind);
378
379#ifndef GPR_LINALG_SCALAPACK
380 // KK =
381 // gp_cov(gp,R_all2,[repmat(R,D+1,1),reshape(repmat(0:D,n,1),[],1)]);
382 KK = trainingCrossCovarianceInFactorRows(R_mod, R_mod_ind,
383 /*serial_per_rank=*/false);
384#endif
385
386 V = observationKernelDiagonal(image1.R);
387 priorFromKernelDiagonal(R_mod, V);
388
389 const bool has_training_factor = R_matrix.rows() > 0 &&
390 R_indices.size() > 0 &&
392 if (!has_training_factor) {
393 VarEG_R = V;
394 } else {
395 // Var = diag(K) - ||L^{-1} K_*||^2. One triangular solve of every
396 // consumed column. The precision form K_*^T (L L^T)^{-1} K_* is the
397 // same quadratic and is not materialized.
398 // VarEG_R = diag(Cov) - sum((L\KK)'.*(L\KK)',2)
399#ifdef GPR_LINALG_SCALAPACK
400 // assembleCrossCovarianceDistributed assumes both x1_ind and x2_ind
401 // come in observation-major: each block-cyclic tile is one observation
402 // with repeating index pattern [0..D]. The training side is permuted
403 // into that layout by prepareTrainingPermutation, but the query R_mod
404 // from assembleMatrixOfRepetitiveCoordinates ships in dim-major (N_im
405 // copies of dim 0, then dim 1, ...). Permute the query into obs-major
406 // for the distributed assemble + solve, then map the variance vector
407 // back to the caller layout.
408 const Index_t n_q = static_cast<Index_t>(image1.R.rows());
409 const Index_t D_q = static_cast<Index_t>(image1.R.cols());
410 const Index_t mod_rows = (D_q + 1) * n_q;
411 std::vector<Index_t> q_perm(mod_rows);
412 for (Index_t k = 0; k < n_q; ++k)
413 for (Index_t i = 0; i <= D_q; ++i)
414 q_perm[k * (D_q + 1) + i] = i * n_q + k;
415
416 EigenMatrix R_mod_perm(R_mod.rows(), R_mod.cols());
417 Eigen::VectorXd R_mod_ind_perm(R_mod_ind.size());
418 for (Index_t r = 0; r < mod_rows; ++r) {
419 R_mod_perm.row(r) = R_mod.row(q_perm[r]);
420 R_mod_ind_perm(r) = R_mod_ind(q_perm[r]);
421 }
422 Eigen::VectorXd V_perm(V.size());
423 for (Index_t r = 0; r < mod_rows; ++r)
424 V_perm(r) = V(q_perm[r]);
425
426 EigenMatrix R_train =
428 Eigen::VectorXd R_train_ind = hasTrainingPermutation()
430 : R_indices;
431 int desc_kk[9];
432 std::vector<double> KK_dist;
433 assembleCrossCovarianceDistributed(R_train, R_mod_perm, R_train_ind,
434 R_mod_ind_perm, KK_dist, desc_kk);
435 Eigen::VectorXd VarEG_perm;
437 VarEG_perm = backend().bordered_cholesky_diagonal_distributed(
438 L, std::move(KK_dist), desc_kk,
439 static_cast<int>(R_train.rows()),
440 static_cast<int>(R_mod_perm.rows()), V_perm);
441 } else {
442 VarEG_perm =
443 V_perm -
444 backend().forward_solve_mat_colwise_squared_norm_distributed(
445 L, std::move(KK_dist), desc_kk,
446 static_cast<int>(R_train.rows()),
447 static_cast<int>(R_mod_perm.rows()));
448 }
449
450 VarEG_R.resize(VarEG_perm.size());
451 for (Index_t r = 0; r < mod_rows; ++r)
452 VarEG_R(q_perm[r]) = VarEG_perm(r);
453#else
454 const EigenMatrix kk_eval =
455 rigid_deflation_.isActiveForFullOrder(KK.rows())
456 ? rigid_deflation_.projectRows(KK)
457 : KK;
459 VarEG_R = trainingSolver().posteriorVarianceDiagonal(kk_eval, V);
460 else
461 VarEG_R = V - trainingSolver().quadraticDiagonal(kk_eval);
462#endif
463 }
464
465 // VarE_R = VarEG_R(1:n,:);
466 // Reported variance carries the same LOO calibration as the HS-SVD
467 // backend (hssvd_variance_calibration_factor_ is backend-independent);
468 // certification code divides it back out through
469 // reportedVarianceCalibrationFactor().
470 VarEG_R *= hssvd_variance_calibration_factor_;
471
472 image1.E.resize(1, n);
473 image1.E = Eigen::Map<const Eigen::RowVectorXd>(VarEG_R.data(), n);
474
475 // G_R = reshape(VarEG_R((n+1):end), n, D);
476 Index_t D = image1.R.cols();
477 image1.G.resize(n, D);
478 image1.G = Eigen::Map<const Eigen::Matrix<double, Eigen::Dynamic,
479 Eigen::Dynamic, Eigen::ColMajor>>(
480 VarEG_R.data() + n, n, D);
481}
EigenMatrix trainingCrossCovarianceInFactorRows(const EigenMatrix &query, const Eigen::VectorXd &query_ind, bool serial_per_rank) const
void calculateVarianceHssvd(Observation &image1)
Eigen::VectorXd posteriorVarianceDiagonal(const EigenMatrix &B, const Eigen::VectorXd &prior) const override
Bordered Cholesky posterior variance diagonal.
Eigen::VectorXd quadraticDiagonal(const EigenMatrix &B) const override
diag(B^T K^{-1} B), the explained part of a posterior variance.

◆ calculateVarianceBatch()

void gpr::GaussianProcessRegression::calculateVarianceBatch ( std::vector< Observation * > queries)

One dispatched variance predict for B same-composition queries.

Definition at line 1142 of file Predict.cpp.

1144{
1145 Observation stacked;
1146 std::vector<Index_t> row_counts;
1147 if (!stackSameCompositionQueries(queries, stacked, row_counts)) return;
1149 unstackEnergyGradient(stacked, queries, row_counts);
1150}
void calculateVarianceDispatched(Observation &image1)

◆ calculateVarianceBMA()

void gpr::GaussianProcessRegression::calculateVarianceBMA ( Observation & image1)

Definition at line 133 of file BMA.cpp.

134{
135 BMAPrediction pred;
136 if (!runBMAGrid(image1, pred)) {
137 calculateMapVarianceInTrainingUnits(image1);
138 return;
139 }
140 const Index_t N_im = static_cast<Index_t>(image1.R.rows());
141 const Index_t D = static_cast<Index_t>(image1.R.cols());
142 // BMA-averaged variance includes both the within-model predictive
143 // variance and the between-model spread of the predictive means
144 // (law of total variance). Clip non-negative since round-off can
145 // produce small negatives near zero-uncertainty query points.
146 Eigen::VectorXd v = pred.variance.cwiseMax(0.0);
147 writeBMAOutput(v, N_im, D, image1);
148}

◆ calculateVarianceDispatched()

void gpr::GaussianProcessRegression::calculateVarianceDispatched ( Observation & image1)

Dispatched variance: calculateVariance (MAP) or calculateVarianceLaplace based on uncertainty_mode_. Dimer certificate consumers call this when both energy and force variance are required.

Definition at line 2000 of file GaussianProcessRegression.cpp.

2001{
2002 ScopedPredictTimer predict_timer;
2003 if (recallCachedVarianceSolve(image1)) return;
2004 ScopedVarianceTimer variance_timer;
2005 if (atomic_environment_model_) {
2006 calculateAtomicEnvironmentVariance(image1);
2007 return;
2008 }
2009 if (active_posterior_) {
2010 calculateActivePosteriorVariance(image1);
2011 return;
2012 }
2013 // RFF-replace path: above the design cutoff the exact dual-kernel
2014 // eigensolve was skipped (rff_replaces_exact_), so the RFF Bayesian
2015 // linear-regression posterior is the only model -- take the variance
2016 // from it. Gated on rff_replaces_exact_ so below-cutoff systems fall
2017 // through to the exact dispatch unchanged.
2018 if (rff_replaces_exact_ && rff_model_.isBuilt()) {
2019 calculateVarianceRFF(image1);
2020 return;
2021 }
2022 // MAP variance uses the fitted stable basis and its physical output
2023 // units. Integrated modes include hyperparameter uncertainty through
2024 // their own posterior operators.
2025 if (uncertainty_mode_ == UncertaintyMode::MAP && canUseHssvdVariance()) {
2026 calculateVarianceHssvd(image1);
2027 return;
2028 }
2029 switch (uncertainty_mode_) {
2031 calculateVarianceSVGD(image1);
2032 break;
2035 // Empirical Bayes uses MAP for the mean (fast, no Taylor
2036 // correction risk on small data) but the LAPLACE mixture
2037 // for the variance, which is the calibrated Bayesian
2038 // estimate including hyperparameter uncertainty. This is the
2039 // standard EB approach (Carlin & Louis 2008; INLA's
2040 // approx hyperpar.dist mode), and is the right default for
2041 // small-data regimes where the TCOV correction on the mean
2042 // is unreliable but the K-grid mixture variance is still
2043 // informative.
2045 break;
2047 if (use_delta_method_) {
2048 calculateVarianceLaplaceDelta(image1);
2049 } else {
2051 }
2052 break;
2054 calculateVarianceBMA(image1);
2055 break;
2057 default:
2058 ensurePosteriorFactorForPrediction();
2059 calculateVariance(image1);
2060 break;
2061 }
2062 // Un-normalize posterior variance from standardized to physical units:
2063 // var(E) = y_scale_^2 var(E~), var(grad) = y_scale_^2 var(grad~).
2064 if (y_scale_ != 1.0) {
2065 const double s2 = y_scale_ * y_scale_;
2066 if (image1.E.size() > 0) image1.E.array() *= s2;
2067 if (image1.G.size() > 0) image1.G.array() *= s2;
2068 }
2069 storeCachedVarianceSolve(image1);
2070}
virtual void calculateVariance(Observation &image1)
Compute predictive variance for energy and gradient. Corresponds to MATLAB get_variance....
Definition Variance.cpp:353
void calculateVarianceLaplace(Observation &image1)
void calculateVarianceBMA(Observation &image1)
Definition BMA.cpp:133
void calculateVarianceRFF(Observation &image)
Definition RFF.cpp:70
void calculateVarianceSVGD(Observation &image1)
Definition SVGD.cpp:167
void calculateVarianceLaplaceSlice(Observation &image1)

◆ calculateVarianceHssvd()

void gpr::GaussianProcessRegression::calculateVarianceHssvd ( Observation & image1)

Stable-basis posterior energy variance, consistent with the HS-SVD mean. var(x*) = k(x*,x*) - k*^T (K+sigma2 I)^{-1} k* via the eigen-form; inflates to magnSigma2 where x* leaves the training data, fixing the over-confidence of routing the mean through the stable basis while the variance still came from the Laplace/Cholesky path. Writes energy variance into image1.E (calculateVariance convention). Requires the serial factorize (A_train retained); callers fall back otherwise.

Definition at line 2266 of file Decompose.cpp.

2267{
2268 const Eigen::Index N_im = image1.R.rows();
2269 const Eigen::Index D = image1.R.cols();
2270 if (N_im <= 0 || D <= 0 || R_matrix.rows() <= 0 ||
2271 R_indices.size() != R_matrix.rows() || hssvd_basis_.rank() <= 0) {
2272 fillConservativeVariance(image1);
2273 return;
2274 }
2275
2276 if (hssvd_dual_kernel_) {
2277 EigenMatrix Kstar;
2278 Eigen::VectorXd prior_diag;
2279 if (assembleHssvdDualFullCrossCovariance(image1.R, Kstar,
2280 &prior_diag) &&
2281 Kstar.rows() == hssvd_basis_.numObs() &&
2282 Kstar.cols() == N_im * (D + 1) &&
2283 prior_diag.size() == Kstar.cols()) {
2284 Eigen::VectorXd observation_noise =
2285 Eigen::VectorXd::Zero(prior_diag.size());
2286 {
2287 EigenMatrix query_rows;
2288 Eigen::VectorXd query_ind;
2289 aux::AuxiliaryFunctionality aux_layout;
2291 image1.R, query_rows, query_ind);
2292 if (query_rows.rows() == prior_diag.size()) {
2293 priorFromKernelDiagonal(query_rows, observation_noise);
2294 prior_diag += observation_noise;
2295 }
2296 }
2297 const double total_sigma2 = totalPosteriorNoiseVariance();
2298 // The allowance tracks the diagonal that is cancelled, which
2299 // already includes observation noise when that noise was added.
2300 const Eigen::VectorXd& signal = prior_diag;
2301 Eigen::VectorXd VarEG_R;
2302 bool ready = false;
2303 std::vector<char> replaced;
2305 stableRangePosteriorDiagonal(hssvd_basis_, Kstar, prior_diag,
2306 signal, N_im, total_sigma2,
2307 VarEG_R);
2308 ready = true;
2309 } else {
2310 const Eigen::VectorXd projected =
2311 rangeSelfQuadraticByChannelBlock(hssvd_basis_, Kstar, N_im,
2312 total_sigma2);
2313 if (projected.size() == Kstar.cols() && projected.allFinite()) {
2314 VarEG_R = prior_diag - projected;
2315 ready = true;
2316 }
2317 }
2318 if (ready) {
2319 // The latent training-row formula replaces the Schur value of
2320 // the channels it matches, so it runs first; the certified
2321 // floor then sees, and counts, only the entries that remain.
2322 if (!applyHssvdTrainingRowLatentVariance(
2323 image1.R, VarEG_R, total_sigma2, &observation_noise,
2324 &replaced))
2325 throw linalg::StableVarianceError(
2326 "stable posterior variance is not finite and "
2327 "nonnegative");
2329 for (Eigen::Index channel = 0; channel < VarEG_R.size();
2330 ++channel)
2331 if (!replaced[static_cast<std::size_t>(channel)])
2333 VarEG_R(channel), signal(channel));
2335 hssvd_basis_.floorCertifiedSchurDiagonal(
2336 Kstar, prior_diag, total_sigma2, VarEG_R, &replaced);
2337
2338 // LOO calibration factor rescales the REPORTED variance only
2339 // (see hssvd_variance_calibration_factor_); the threshold
2340 // that gates against it must stay in the model's own units.
2342 image1.E.resize(1, N_im);
2343 image1.E =
2344 Eigen::Map<const Eigen::RowVectorXd>(VarEG_R.data(), N_im);
2345 image1.G.resize(N_im, D);
2346 image1.G = Eigen::Map<const Eigen::Matrix<
2347 double, Eigen::Dynamic, Eigen::Dynamic, Eigen::ColMajor>>(
2348 VarEG_R.data() + N_im, N_im, D);
2349 return;
2350 }
2351 }
2352 }
2353
2354 aux::AuxiliaryFunctionality aux_func;
2355 EigenMatrix R_mod;
2356 Eigen::VectorXd R_mod_ind;
2357 aux_func.assembleMatrixOfRepetitiveCoordinates(image1.R, R_mod, R_mod_ind);
2358 if (R_mod.rows() != N_im * (D + 1) || R_mod_ind.size() != R_mod.rows()) {
2359 fillConservativeVariance(image1);
2360 return;
2361 }
2362
2363 EigenMatrix Kstar;
2364 evaluateCovarianceMatrix(R_matrix, R_mod, R_indices, R_mod_ind, Kstar,
2365 /*serial_per_rank=*/true);
2366 if (Kstar.rows() != hssvd_basis_.numObs() || Kstar.cols() != R_mod.rows()) {
2367 fillConservativeVariance(image1);
2368 return;
2369 }
2370
2371 Eigen::VectorXd prior_diag = observationKernelDiagonal(image1.R);
2372 if (prior_diag.size() != R_mod.rows()) {
2373 fillConservativeVariance(image1);
2374 return;
2375 }
2376
2377 const double total_sigma2 = totalPosteriorNoiseVariance();
2378 // R_mod is dim-major, so its first N_im rows are the energy channels.
2379 Eigen::VectorXd projected;
2381 projected = rangeSelfQuadraticByChannelBlock(hssvd_basis_, Kstar, N_im,
2382 total_sigma2);
2383 if (projected.size() != R_mod.rows()) {
2384 fillConservativeVariance(image1);
2385 return;
2386 }
2387 }
2388
2389 Eigen::VectorXd observation_noise =
2390 Eigen::VectorXd::Zero(prior_diag.size());
2391 priorFromKernelDiagonal(R_mod, observation_noise);
2392 prior_diag += observation_noise;
2393 // The allowance tracks the diagonal that is cancelled, which already
2394 // includes observation noise.
2395 const Eigen::VectorXd& signal = prior_diag;
2396 Eigen::VectorXd VarEG_R;
2398 stableRangePosteriorDiagonal(hssvd_basis_, Kstar, prior_diag, signal,
2399 N_im, total_sigma2, VarEG_R);
2400 } else {
2401 VarEG_R = prior_diag - projected;
2402 }
2403 std::vector<char> replaced;
2404 if (!applyHssvdTrainingRowLatentVariance(image1.R, VarEG_R, total_sigma2,
2405 &observation_noise, &replaced))
2406 throw linalg::StableVarianceError(
2407 "stable posterior variance is not finite and nonnegative");
2409 for (Eigen::Index channel = 0; channel < VarEG_R.size(); ++channel)
2410 if (!replaced[static_cast<std::size_t>(channel)])
2412 signal(channel));
2414 hssvd_basis_.floorCertifiedSchurDiagonal(
2415 Kstar, prior_diag, total_sigma2, VarEG_R, &replaced);
2416
2417 // LOO calibration factor rescales the REPORTED variance only (see
2418 // hssvd_variance_calibration_factor_); the threshold that gates against
2419 // it must stay in the model's own units.
2421
2422 image1.E.resize(1, N_im);
2423 image1.E = Eigen::Map<const Eigen::RowVectorXd>(VarEG_R.data(), N_im);
2424 image1.G.resize(N_im, D);
2425 image1.G = Eigen::Map<const Eigen::Matrix<double, Eigen::Dynamic,
2426 Eigen::Dynamic, Eigen::ColMajor>>(
2427 VarEG_R.data() + N_im, N_im, D);
2428}
void scaleTrainingVarianceToPhysical(Eigen::Ref< Eigen::VectorXd > variance) const
void requireStablePosteriorVariance(double &variance, double signal_variance, double relative_allowance)
Accept one stable posterior variance or throw.
Definition ExactSchur.h:131

◆ calculateVarianceLaplace()

void gpr::GaussianProcessRegression::calculateVarianceLaplace ( Observation & image1)

Laplace-mixture predictive variance (law of total variance over the CCD grid centred at theta*). Same shape contract as calculateVariance: writes per-test-point variance into image1.E (N_im scalars) and per-dim gradient variance into image1.G (N_im x D). Falls back to calculateVariance (MAP) if no Laplace fit can be built.

Definition at line 1196 of file LaplacePosterior.cpp.

1197{
1198 if (!ensureLaplacePosterior()) {
1199 calculateMapVarianceInTrainingUnits(image1);
1200 return;
1201 }
1202
1203 Observation mean_out = image1;
1204 Observation variance_out = image1;
1205 if (!calculateLaplacePosteriorMoments(*laplace_posterior_, image1, mean_out,
1206 &variance_out)) {
1207 calculateMapVarianceInTrainingUnits(image1);
1208 return;
1209 }
1210 image1.E = variance_out.E;
1211 image1.G = variance_out.G;
1212}

◆ calculateVarianceLaplaceSlice()

void gpr::GaussianProcessRegression::calculateVarianceLaplaceSlice ( Observation & image1)

Variance counterpart to calculatePotentialLaplaceSlice. Reports the between-sample variance of the per-sample mean predictions (Var_theta[mu(theta; x*)]); the within-sample variance is left for a follow-up since it requires K^-1 k_cross per sample per query (one extra triangular solve each, doubling per-predict cost). The between-sample variance is the dominant component when the hyperparameter posterior is broad (which is the only regime where LAPLACE differs meaningfully from MAP), so the approximation is fit-for-purpose for the variance-gated acquisition path.

Definition at line 762 of file LaplaceSlice.cpp.

764{
765 if (!runSliceLaplacePredict(image1, /*want_variance=*/true)) {
766 calculateMapVarianceInTrainingUnits(image1);
767 return;
768 }
769}

◆ calculateVarianceRFF()

void gpr::GaussianProcessRegression::calculateVarianceRFF ( Observation & image)

Definition at line 70 of file RFF.cpp.

71{
72 // Pass-through: RFFModel writes the BLR predictive variance into
73 // image1.E / image1.G. For the LAPLACE_SLICE + INLA-Delta arm the
74 // dispatch routes variance through calculateVarianceLaplaceDelta
75 // instead (calibrated hyperparameter posterior) and only uses the
76 // RFF variance on the bare-GP arm. Kept for completeness so the
77 // RFF path is self-contained.
78 rff_model_.calculateVariance(image1);
79 if (rff_standardized_targets_) {
80 const double scale =
81 (std::isfinite(y_scale_) && y_scale_ > 0.0) ? y_scale_ : 1.0;
82 const double scale_sq = scale * scale;
83 if (scale_sq != 1.0) {
84 if (image1.E.size() > 0) image1.E *= scale_sq;
85 if (image1.G.size() > 0) image1.G *= scale_sq;
86 }
87 }
88}

◆ calculateVarianceSVGD()

void gpr::GaussianProcessRegression::calculateVarianceSVGD ( Observation & image1)

Definition at line 167 of file SVGD.cpp.

168{
169 // Variance via the law of total variance over SVGD particles.
170 LaplaceINLA local_laplace;
171 if (!fitLaplaceFromScratch(local_laplace)) {
172 Observation mean_out = image1;
173 Observation variance_out = image1;
174 if (usesRankOwnedMixturePosterior() &&
175 calculateRankOwnedMapPosteriorMoments(image1, mean_out,
176 &variance_out)) {
177 image1.E = variance_out.E;
178 image1.G = variance_out.G;
179 return;
180 }
181 calculateMapVarianceInTrainingUnits(image1);
182 return;
183 }
184 laplace::SteinVariational local_svgd;
185 if (!fitSVGDFromScratch(local_laplace, local_svgd)) {
186 Observation mean_out = image1;
187 Observation variance_out = image1;
188 if (usesRankOwnedMixturePosterior() &&
189 calculateRankOwnedMapPosteriorMoments(image1, mean_out,
190 &variance_out)) {
191 image1.E = variance_out.E;
192 image1.G = variance_out.G;
193 return;
194 }
195 calculateMapVarianceInTrainingUnits(image1);
196 return;
197 }
198 const auto& particles = local_svgd.particles();
199 if (particles.empty() || R_matrix.size() == 0 ||
200 energy_and_gradient.size() == 0) {
201 Observation mean_out = image1;
202 Observation variance_out = image1;
203 if (usesRankOwnedMixturePosterior() &&
204 calculateRankOwnedMapPosteriorMoments(image1, mean_out,
205 &variance_out)) {
206 image1.E = variance_out.E;
207 image1.G = variance_out.G;
208 return;
209 }
210 calculateMapVarianceInTrainingUnits(image1);
211 return;
212 }
213 const LaplacePosteriorSignature signature =
214 currentLaplacePosteriorSignature();
216 if (!buildUniformParticlePosteriorState(particles, signature, state)) {
217 Observation mean_out = image1;
218 Observation variance_out = image1;
219 if (usesRankOwnedMixturePosterior() &&
220 calculateRankOwnedMapPosteriorMoments(image1, mean_out,
221 &variance_out)) {
222 image1.E = variance_out.E;
223 image1.G = variance_out.G;
224 return;
225 }
226 calculateMapVarianceInTrainingUnits(image1);
227 return;
228 }
229 Observation mean_out = image1;
230 Observation variance_out = image1;
231 if (!calculateLaplacePosteriorMoments(state, image1, mean_out,
232 &variance_out)) {
233 if (usesRankOwnedMixturePosterior() &&
234 calculateRankOwnedMapPosteriorMoments(image1, mean_out,
235 &variance_out)) {
236 image1.E = variance_out.E;
237 image1.G = variance_out.G;
238 return;
239 }
240 calculateMapVarianceInTrainingUnits(image1);
241 return;
242 }
243 image1.E = variance_out.E;
244 image1.G = variance_out.G;
245}

◆ calibrateHeldOutForces()

GaussianProcessRegression::ForceCalibrationReport gpr::GaussianProcessRegression::calibrateHeldOutForces ( const Observation & held_out,
double nominal_probability )
nodiscard

Compare held-out true Cartesian gradients with the posterior force marginal. The scale is sqrt(mean(z^2)) for z=(F_true-F_mean)/sd=(G_mean-G_true)/sd and is not clipped or regularized.

Definition at line 1156 of file Optimize.cpp.

1158{
1159 const double central_probability = 0.5 * (1.0 + nominal_probability);
1160 if (!(nominal_probability > 0.0 && nominal_probability < 1.0) ||
1161 !(central_probability < 1.0) || held_out.R.rows() <= 0 ||
1162 held_out.R.cols() <= 0 || held_out.G.rows() != held_out.R.rows() ||
1163 held_out.G.cols() != held_out.R.cols() || !held_out.R.allFinite() ||
1164 !held_out.G.allFinite()) {
1165 throw std::invalid_argument(
1166 "held-out force calibration requires finite matching positions "
1167 "and gradients and a nominal probability in (0,1)");
1168 }
1169
1170 Observation mean;
1171 mean.R = held_out.R;
1173 struct RestoreVarianceConvention {
1174 GaussianProcessRegression& model;
1175 VarianceConvention saved;
1176 ~RestoreVarianceConvention()
1177 {
1178 model.setVarianceConvention(saved);
1179 }
1180 } restore_variance{*this, varianceConvention()};
1182 Observation variance;
1183 variance.R = held_out.R;
1185 if (mean.G.rows() != held_out.G.rows() ||
1186 mean.G.cols() != held_out.G.cols() ||
1187 variance.G.rows() != held_out.G.rows() ||
1188 variance.G.cols() != held_out.G.cols()) {
1189 throw std::runtime_error("held-out force prediction shape mismatch");
1190 }
1191
1192 const double reported_scale = reportedVarianceCalibrationFactor();
1193 if (!(reported_scale > 0.0) || !std::isfinite(reported_scale))
1194 throw std::runtime_error("posterior variance scale is invalid");
1195 const double quantile = math::DistributionFunctions().normalCDFInverse(
1196 central_probability, 0.0, 1.0);
1197 double sum = 0.0;
1198 double sumsq = 0.0;
1199 double sum_log_predictive_density = 0.0;
1200 std::size_t covered = 0;
1201 std::vector<double> standardized;
1202 standardized.reserve(static_cast<std::size_t>(held_out.G.size()));
1203 for (Eigen::Index row = 0; row < held_out.G.rows(); ++row) {
1204 for (Eigen::Index col = 0; col < held_out.G.cols(); ++col) {
1205 const double raw_variance = variance.G(row, col) / reported_scale;
1206 // A kernel may make symmetry-protected force components exactly
1207 // deterministic. They carry no calibration information when the
1208 // residual is also exactly zero, so omit them without introducing
1209 // a numerical variance floor.
1210 const double residual = mean.G(row, col) - held_out.G(row, col);
1211 if (raw_variance == 0.0 && residual == 0.0) continue;
1212 if (!(raw_variance > 0.0) || !std::isfinite(raw_variance))
1213 throw std::runtime_error(
1214 "held-out posterior force variance is not positive at "
1215 "component " +
1216 std::to_string(row * held_out.G.cols() + col) + ": " +
1217 std::to_string(raw_variance));
1218 // Force residual F_true-F_mean equals G_mean-G_true.
1219 const double z = residual / std::sqrt(raw_variance);
1220 if (!std::isfinite(z))
1221 throw std::runtime_error(
1222 "held-out standardized force residual is not finite");
1223 standardized.push_back(z);
1224 sum += z;
1225 sumsq += z * z;
1226 sum_log_predictive_density -=
1227 0.5 * (numerics::log(2.0 * M_PI * raw_variance) + z * z);
1228 if (std::abs(z) <= quantile) ++covered;
1229 }
1230 }
1231 if (standardized.empty())
1232 throw std::runtime_error(
1233 "held-out force calibration has no stochastic components");
1234
1236 report.components = standardized.size();
1237 report.nominal_probability = nominal_probability;
1238 report.posterior_variance_scale = reported_scale;
1239 report.mean_standardized_residual =
1240 sum / static_cast<double>(report.components);
1241 report.rms_standardized_residual =
1242 std::sqrt(sumsq / static_cast<double>(report.components));
1243 report.calibration_scale = report.rms_standardized_residual;
1244 report.mean_log_predictive_density =
1245 sum_log_predictive_density / static_cast<double>(report.components);
1246 report.empirical_coverage =
1247 static_cast<double>(covered) / static_cast<double>(report.components);
1248 std::size_t calibrated_covered = 0;
1249 for (const double z: standardized)
1250 if (std::abs(z) <= quantile * report.calibration_scale)
1251 ++calibrated_covered;
1252 report.calibrated_coverage = static_cast<double>(calibrated_covered) /
1253 static_cast<double>(report.components);
1254 return report;
1255}
double reportedVarianceCalibrationFactor() const noexcept
void setVarianceConvention(VarianceConvention convention) noexcept
VarianceConvention varianceConvention() const noexcept
double variance(const Weights &w, const Matrix &covariance)
Componentwise held-out force calibration in physical units.

◆ calibrateLeaveOneOut()

GaussianProcessRegression::LeaveOneOutCalibrationReport gpr::GaussianProcessRegression::calibrateLeaveOneOut ( double nominal_probability) const
nodiscard

Evaluate all training channels by closed-form leave-one-out prediction from the active posterior's inverse diagonal and weights.

Definition at line 1153 of file Predict.cpp.

1155{
1156 const double central_probability = 0.5 * (1.0 + nominal_probability);
1157 if (!(nominal_probability > 0.0 && nominal_probability < 1.0) ||
1158 !std::isfinite(nominal_probability) || !(central_probability < 1.0)) {
1159 throw std::invalid_argument(
1160 "LOO calibration requires a representable central Gaussian "
1161 "probability in (0, 1)");
1162 }
1163
1164#ifdef GPR_LINALG_KOKKOS
1166#endif
1167 Eigen::VectorXd weights;
1168 Eigen::VectorXd inverse_diagonal;
1169 if (use_hssvd_backend_ && hssvd_basis_valid_ &&
1170 energy_and_gradient.size() > 0 && hssvd_basis_.rank() > 0 &&
1171 hssvd_basis_.numObs() == energy_and_gradient.size()) {
1172 const double total_noise_variance = totalPosteriorNoiseVariance();
1173 weights =
1174 hssvd_basis_.solveNoisy(energy_and_gradient, total_noise_variance);
1175 inverse_diagonal =
1176 hssvd_basis_.noisyInverseDiagonal(total_noise_variance);
1177 } else if (a.size() > 0 && hasTrainingCholeskyFactor(a.size())) {
1178 weights = rigid_deflation_.isActiveForFullOrder(a.size())
1179 ? (a + rigid_deflation_.a_rigid).eval()
1180 : a;
1181 inverse_diagonal = trainingInverseDiagonalInFactorLayout();
1182 } else {
1183 throw std::runtime_error(
1184 "closed-form LOO calibration requires a trained GP posterior");
1185 }
1186 if (weights.size() == 0 || weights.size() != inverse_diagonal.size()) {
1187 throw std::runtime_error(
1188 "closed-form LOO inverse diagonal size mismatch");
1189 }
1190
1191 const double physical_variance_scale = outputVarianceScaleSquared();
1192 if (!(physical_variance_scale > 0.0) ||
1193 !std::isfinite(physical_variance_scale)) {
1194 throw std::runtime_error("posterior output variance scale is invalid");
1195 }
1196 const double quantile = math::DistributionFunctions().normalCDFInverse(
1197 central_probability, 0.0, 1.0);
1198 if (!(quantile > 0.0) || !std::isfinite(quantile))
1199 throw std::runtime_error("normal quantile is invalid");
1200
1201 std::vector<double> standardized;
1202 standardized.reserve(static_cast<std::size_t>(weights.size()));
1203 double sum = 0.0;
1204 double sumsq = 0.0;
1205 double sum_log_predictive_density = 0.0;
1206 std::size_t covered = 0;
1207 for (Eigen::Index index = 0; index < weights.size(); ++index) {
1208 const double inverse_variance = inverse_diagonal(index);
1209 const double weight = weights(index);
1210 if (!(inverse_variance > 0.0) || !std::isfinite(inverse_variance) ||
1211 !std::isfinite(weight)) {
1212 throw std::runtime_error(
1213 "closed-form LOO calibration encountered a non-positive "
1214 "inverse diagonal or non-finite weight");
1215 }
1216 // Rasmussen & Williams (2006), eq. 5.12:
1217 // y_i - mu_{-i} = alpha_i / q_i and var_{-i} = 1 / q_i.
1218 const double z = weight / std::sqrt(inverse_variance);
1219 const double physical_variance =
1220 physical_variance_scale / inverse_variance;
1221 const double log_predictive_density =
1222 -0.5 * (std::log(2.0 * M_PI * physical_variance) + z * z);
1223 if (!std::isfinite(z) || !std::isfinite(log_predictive_density))
1224 throw std::runtime_error(
1225 "closed-form LOO residual or log predictive density is "
1226 "non-finite");
1227 standardized.push_back(z);
1228 sum += z;
1229 sumsq += z * z;
1230 sum_log_predictive_density += log_predictive_density;
1231 if (std::abs(z) <= quantile) ++covered;
1232 }
1233
1234 const double count = static_cast<double>(standardized.size());
1235 const double rms = std::sqrt(sumsq / count);
1236 std::size_t calibrated_covered = 0;
1237 for (const double z: standardized)
1238 if (std::abs(z) <= quantile * rms) ++calibrated_covered;
1239
1241 report.components = standardized.size();
1242 report.nominal_probability = nominal_probability;
1243 report.empirical_coverage = static_cast<double>(covered) / count;
1244 report.calibrated_coverage =
1245 static_cast<double>(calibrated_covered) / count;
1246 report.calibration_scale = rms;
1247 report.mean_standardized_residual = sum / count;
1248 report.rms_standardized_residual = rms;
1249 report.mean_log_predictive_density = sum_log_predictive_density / count;
1250 return report;
1251}
const Eigen::VectorXd & trainingInverseDiagonalInFactorLayout() const
Definition Predict.cpp:523

◆ canCertifyEnergyVarianceInterval()

bool gpr::GaussianProcessRegression::canCertifyEnergyVarianceInterval ( ) const
nodiscard

Whether tryGateEnergyVarianceInterval can certify this model: an exact-kernel HS-SVD MAP posterior with no replacement path active.

Definition at line 799 of file Variance.cpp.

800{
801 return !(atomic_environment_model_ || active_posterior_ ||
802 (sexpat_cov_func && sexpat_cov_func->usesManifoldChart()) ||
803 (rff_replaces_exact_ && rff_model_.isBuilt()) ||
804 uncertainty_mode_ != UncertaintyMode::MAP ||
805 R_matrix.rows() <= 0 || R_indices.size() != R_matrix.rows() ||
806 !canUseHssvdVariance() ||
807 !hssvd_basis_.supportsBorderedVarianceInterval());
808}

◆ canUseDevicePosterior()

bool gpr::GaussianProcessRegression::canUseDevicePosterior ( ) const
nodiscardprotected

Definition at line 290 of file DevicePosterior.cpp.

291{
292 return false;
293}

◆ canUseTrainingGeometryObjective()

bool gpr::GaussianProcessRegression::canUseTrainingGeometryObjective ( ) const
nodiscardprotectednoexcept

Definition at line 389 of file Optimize.cpp.

390{
391 return typeid(*this) == typeid(GaussianProcessRegression);
392}

◆ captureFittedHyperparameterDensity()

void gpr::GaussianProcessRegression::captureFittedHyperparameterDensity ( const Coord & positions,
const Eigen::VectorXd & targets,
const Eigen::VectorXd & theta,
const funcmin::MapObjectiveConfig & penalty,
double target_scale,
bool use_ties )
protected

Definition at line 771 of file LaplaceSlice.cpp.

775{
776 fitted_hyperparameter_density_.reset();
777 if (!retain_fitted_hyperparameter_density_) return;
778 slice_laplace_state_.reset();
779 if (failedOptimizer || sexpat_cov_func == nullptr ||
780 lik_gaussian == nullptr || positions.rows() <= 0 ||
781 positions.cols() <= 0 ||
782 targets.size() != positions.rows() * (positions.cols() + 1) ||
783 !positions.allFinite() || !targets.allFinite() || !theta.allFinite() ||
784 !(target_scale > 0.0) || !std::isfinite(target_scale) ||
785 hyperparameter_objective_mode_ != HyperparameterObjectiveMode::NLML ||
786 use_hssvd_backend_ || use_correction_ || robust_nu_ > 0.0 ||
787 use_chem_factorized_hyper_ || rff_features_requested_ > 0 ||
788 rff_auto_ || sexpat_cov_func->usesManifoldChart() ||
789 sexpat_cov_func->geodesicHeatKernel() != nullptr ||
790 atoms_config.pair_cutoff > 0.0 ||
791 !funcmin::mapParametersInDomain(theta, penalty)) {
792 return;
793 }
794 const Eigen::Index covariance_count =
795 sexpat_cov_func->combineParameters().size();
796 const Eigen::Index length_count = covariance_count - 1;
797 if (theta.size() != covariance_count &&
798 !(lik_gaussian->getOptimizeSigma2() &&
799 theta.size() == covariance_count + 1)) {
800 return;
801 }
802 auto density = std::make_unique<FittedHyperparameterDensity>();
803 density->parameter_group.assign(static_cast<std::size_t>(theta.size()), -1);
804 std::vector<Eigen::Index> columns(static_cast<std::size_t>(theta.size()),
805 -1);
806 const bool tied = use_ties && lengthScaleTiesActive(length_count);
807 for (Eigen::Index i = 0; i < theta.size(); ++i) {
808 const Eigen::Index leader =
809 tied && i > 0 && i <= length_count
810 ? 1 + length_scale_ties_.leader[static_cast<std::size_t>(i - 1)]
811 : i;
812 const bool masked =
813 penalty.active_parameters.size() ==
814 static_cast<std::size_t>(theta.size()) &&
815 !penalty.active_parameters[static_cast<std::size_t>(leader)];
816 const bool fixed =
817 penalty.parameter_lower.size() == theta.size() &&
818 penalty.parameter_upper.size() == theta.size() &&
819 penalty.parameter_lower(leader) == penalty.parameter_upper(leader);
820 if (masked || fixed) continue;
821 // An interior Gaussian approximation has no free coordinate on a box
822 // face.
823 if ((penalty.parameter_lower.size() == theta.size() &&
824 !(theta(i) > penalty.parameter_lower(i))) ||
825 (penalty.parameter_upper.size() == theta.size() &&
826 !(theta(i) < penalty.parameter_upper(i)))) {
827 return;
828 }
829 auto& column = columns[static_cast<std::size_t>(leader)];
830 if (column < 0) column = density->free_count++;
831 density->parameter_group[static_cast<std::size_t>(i)] = column;
832 }
833 if (density->free_count == 0) return;
834 density->positions = positions;
835 density->targets = targets;
836 density->theta = theta;
837 density->posterior_theta = theta;
838 density->posterior_theta(0) += 2.0 * std::log(target_scale);
839 if (theta.size() > covariance_count)
840 density->posterior_theta(theta.size() - 1) +=
841 2.0 * std::log(target_scale);
842 density->penalty = penalty;
843 density->configuration = atoms_config;
844 // The fit is finished; retain its kernel state without distance scratch.
845 sexpat_cov_func->clearDistanceCache();
846 density->kernel = std::make_unique<SexpatCF>(*sexpat_cov_func);
847 density->kernel->setParameters(theta.head(covariance_count));
848 density->likelihood_sigma2 = lik_gaussian->getSigma2();
849 density->learn_likelihood_noise = lik_gaussian->getOptimizeSigma2();
850 density->constant_sigma2 =
851 const_cov_fun ? const_cov_fun->getConstSigma2() : 0.0;
852 density->jitter_sigma2 = jitter_sigma2;
853 density->target_scale = target_scale;
854 density->principled_nugget = principled_nugget_;
855 density->kappa_max = kappa_max_;
856 density->model_profile = model_profile_;
857 fitted_hyperparameter_density_ = std::move(density);
858}
bool lengthScaleTiesActive(Eigen::Index length_count) const noexcept
bool mapParametersInDomain(const Eigen::VectorXd &w, const MapObjectiveConfig &cfg)
Eigen::VectorXd parameter_lower
Eigen::VectorXd parameter_upper
std::vector< bool > active_parameters

◆ chooseFarthestPointDeterministic()

int gpr::GaussianProcessRegression::chooseFarthestPointDeterministic ( const std::vector< std::pair< int, double > > & candidate_distances,
double tolerance = 1e-12 )
staticprotected

Definition at line 1524 of file Optimize.cpp.

1527{
1528 double max_min_dist = -std::numeric_limits<double>::infinity();
1529 int farthest_point_idx = -1;
1530
1531 for (const auto& [idx, dist]: candidate_distances) {
1532 if (dist > max_min_dist + tolerance) {
1533 max_min_dist = dist;
1534 farthest_point_idx = idx;
1535 continue;
1536 }
1537
1538 if (std::abs(dist - max_min_dist) <= tolerance &&
1539 (farthest_point_idx == -1 || idx < farthest_point_idx)) {
1540 farthest_point_idx = idx;
1541 }
1542 }
1543
1544 return farthest_point_idx;
1545}

◆ claimActiveTrainingCholeskyFactor()

void gpr::GaussianProcessRegression::claimActiveTrainingCholeskyFactor ( )

Associate the live ScaLAPACK factor with this GP after a materialize.

Definition at line 358 of file Decompose.cpp.

359{
360#ifdef GPR_LINALG_SCALAPACK
361 if (!training_cholesky_is_distributed_) return;
362 auto& state = backend().distributed();
363 if (state.has_cached_L() &&
364 state.cached_n() == static_cast<int>(R_matrix.rows()) &&
365 state.cached_L_is_unowned()) {
366 state.claim_cached_L(this);
367 }
368#endif
369}

◆ clearConditionedHessians()

void gpr::GaussianProcessRegression::clearConditionedHessians ( )
noexcept

Definition at line 185 of file GaussianProcessRegression.cpp.

186{
187 if (optimizer_state_) optimizer_state_->conditioned_hessians.clear();
188}

◆ clearGeodesicHeatPrior()

void gpr::GaussianProcessRegression::clearGeodesicHeatPrior ( )

Remove the additive geodesic covariance and restore the configured base-kernel execution backend for hyperparameter fitting.

Definition at line 2222 of file GaussianProcessRegression.cpp.

2223{
2224 if (sexpat_cov_func)
2225 setGeodesicHeatPrior(nullptr);
2226 else
2227 restoreBaseKernelExecutionConfig();
2228}
void setGeodesicHeatPrior(std::shared_ptr< const GeodesicHeatEnergyForceKernel > kernel)

◆ clearHierarchicalPrior()

void gpr::GaussianProcessRegression::clearHierarchicalPrior ( )

Disable the hierarchical prior set via ~setHierarchicalPrior~. Restores the flat prior path on the SExp kernel.

Definition at line 2080 of file GaussianProcessRegression.cpp.

2081{
2082 if (sexpat_cov_func != nullptr) {
2083 sexpat_cov_func->clearHierarchicalPrior();
2084 }
2085}

◆ clearModeRefitHint()

void gpr::GaussianProcessRegression::clearModeRefitHint ( )
inlinenoexcept

Definition at line 565 of file GaussianProcessRegression.h.

566 {
567 scg_opt_settings.active_parameters.clear();
568 active_refit_lengths_.clear();
569 active_refit_setup_skipped_ = false;
570 residual_model_refit_ = false;
571 }

◆ clearOptimizationRequiredRows()

void gpr::GaussianProcessRegression::clearOptimizationRequiredRows ( )
inlinenoexcept

Definition at line 561 of file GaussianProcessRegression.h.

◆ clearOptimizationRowPool()

void gpr::GaussianProcessRegression::clearOptimizationRowPool ( )
inlinenoexcept

Definition at line 545 of file GaussianProcessRegression.h.

546 {
548 }

◆ clearSecantQuadraticPrior()

void gpr::GaussianProcessRegression::clearSecantQuadraticPrior ( )
noexcept

Definition at line 825 of file GaussianProcessRegression.cpp.

826{
827 secant_quadratic_prior_active_ = false;
828 secant_reference_position_.resize(0);
829 secant_reference_gradient_.resize(0);
830 secant_hessian_.resize(0, 0);
831 secant_reference_energy_ = 0.0;
832}

◆ clearTrainingCholeskyFactor()

void gpr::GaussianProcessRegression::clearTrainingCholeskyFactor ( )
protected

Definition at line 243 of file Decompose.cpp.

244{
245 L.resize(0, 0);
246 rigid_deflation_.reset();
247#ifdef GPR_LINALG_KOKKOS
249 device_posterior_.reset();
250#endif
251}
std::shared_ptr< const linalg::KokkosFactor > resident_training_factor_

◆ computeInlaPosteriorMode()

bool gpr::GaussianProcessRegression::computeInlaPosteriorMode ( const EigenMatrix & x,
const Eigen::VectorXd & x_ind,
const Eigen::VectorXd & y,
Eigen::VectorXd & theta_mode,
const TrainingKernelGeometry * training_geom )
protected

Definition at line 234 of file INLA.cpp.

238{
239 theta_mode.resize(0);
240 if (wallClockLimitReached()) return false;
241 if (sexpat_cov_func == nullptr || y.rows() != x.rows()) return false;
242
243 laplace::ScopedKernelState kernel_guard(*sexpat_cov_func, sigma2,
244 lik_gaussian.get());
245 Eigen::VectorXd theta_seed = packInlaHyperparameters();
246 if (theta_seed.size() == 0 || !theta_seed.allFinite()) return false;
247
248 aux::Distance distance;
249 FieldMatrixd unit_lengthscale(1, 1);
250 unit_lengthscale.setConstant(1.0);
251 const double range_x = distance.range_at(x, atoms_config, unit_lengthscale);
252 const double min_lengthscale = inlaMinimumLengthScale(range_x);
253 Eigen::VectorXd lower;
254 Eigen::VectorXd upper;
255 calculateInlaModeLogBounds(theta_seed, min_lengthscale * 1.05,
256 inlaMaxLogMagnSigma2(x, y, theta_seed), lower,
257 upper);
258 const int p = static_cast<int>(theta_seed.size());
259 if (lower.size() != p || upper.size() != p) return false;
260
261 auto clip_to_bounds = [&](const Eigen::VectorXd& theta) {
262 return inlaClipToLogBox(theta, lower, upper);
263 };
264
265 // Warm-start from the last successful mode. Newton/RFO rebuilds H
266 // each step.
267 const bool can_warm_start = inla_warm_valid_ &&
268 inla_warm_theta_.size() == p &&
269 inla_warm_theta_.allFinite();
270 Eigen::VectorXd theta =
271 clip_to_bounds(can_warm_start ? inla_warm_theta_ : theta_seed);
272 if (theta.size() != p || !theta.allFinite()) return false;
273 if (can_warm_start) {
274 ++inla_warm_start_hits_for_testing_;
275 } else {
276 ++inla_warm_start_misses_for_testing_;
277 }
278
279 constexpr int kMaxIterations = 10;
280 constexpr double kGradientTolerance = 1.0e-4;
281 constexpr double kTrustRadius = 3.0;
282
283 std::vector<double> wbuf(static_cast<std::size_t>(p));
284 Eigen::Map<Eigen::VectorXd>(wbuf.data(), p) = theta;
287 rgmin_tensor_borrow_cpu_f64(wbuf.data(), wbuf.size()));
288 if (!xt) return false;
289
290 InlaDestCtx ctx;
291 ctx.gp = this;
292 ctx.x = &x;
293 ctx.x_ind = &x_ind;
294 ctx.y = &y;
295 ctx.geom = training_geom;
296 ctx.p = p;
297
298 rgmin::Control ctrl;
299 ctrl.maxiter = static_cast<std::size_t>(kMaxIterations);
300 ctrl.gtol = kGradientTolerance;
301 ctrl.istep = 1.0;
302 ctrl.memory = 0;
303 // Hyperparameters, not atoms: no step cap of any kind.
304 ctrl.maxmove = -1.0;
305
306 Eigen::VectorXd best_theta = theta;
307 double best_phi = std::numeric_limits<double>::infinity();
308 Eigen::MatrixXd inverse_hessian = Eigen::MatrixXd::Identity(p, p);
309 ctx.failure.invoke("INLA initial objective", [&] {
310 ctx.evalAt(theta);
311 return RGMIN_SUCCESS;
312 });
313 if (ctx.failure.failed() || !ctx.factor_ok) {
314 ctx.failure.report();
315 return false;
316 }
317 best_phi = ctx.cached_energy;
318 try {
319 rgmin::Solver session(rgmin::Method::Rfo, ctrl,
320 static_cast<std::size_t>(p));
321 session.set_accept(RGMIN_ACCEPT_ENERGY);
322 if (session.set_highs(true) != 0 ||
323 session.set_box(lower.data(), upper.data(),
324 static_cast<std::size_t>(p)) != 0) {
325 return false;
326 }
327 session.set_trust(kTrustRadius);
328
329 rgmin::Report report{};
330 for (int iter = 0; iter < kMaxIterations; ++iter) {
331 if (wallClockLimitReached()) return false;
332 last_inla_iterations_ = static_cast<std::size_t>(iter + 1);
333 report =
334 session.step_hess_fg(&inlaEvalGrad, &inlaHess, &ctx, xt.get());
335 if (ctx.failure.failed()) {
336 ctx.failure.report();
337 return false;
338 }
339 Eigen::Map<const Eigen::VectorXd> walked(wbuf.data(), p);
340 if (walked.size() == p && walked.allFinite() &&
341 std::isfinite(report.value) && report.value < best_phi) {
342 best_phi = report.value;
343 best_theta = walked;
344 }
345 if (report.grad_norm <=
346 kGradientTolerance * (1.0 + std::abs(report.value))) {
347 break;
348 }
349 }
350 } catch (...) {
351 ctx.failure.report();
352 return false;
353 }
354 // dest set_box owns the log-box. A walk that leaves it is a dest
355 // failure, not a reason to clip the iterate after the fact.
356 if (best_theta.size() != p || !best_theta.allFinite()) {
357 return false;
358 }
359 for (int i = 0; i < p; ++i) {
360 if (best_theta(i) < lower(i) - 1.0e-12 ||
361 best_theta(i) > upper(i) + 1.0e-12) {
362 return false;
363 }
364 }
365
366 if (!std::isfinite(best_phi) || best_theta.size() != p ||
367 !best_theta.allFinite()) {
368 return false;
369 }
370
371 setParameters(best_theta);
372 const double phi_mode = evaluateEnergy(x, x_ind, y);
373 if (!std::isfinite(phi_mode) || !is_decomposed_succesfully) {
374 return false;
375 }
376 theta_mode = best_theta;
377 if (retain_fitted_hyperparameter_density_) {
378 funcmin::MapObjectiveConfig density_config;
379 density_config.barrier_strength = 0.0;
381 density_config.parameter_lower = lower;
382 density_config.parameter_upper = upper;
383 const Eigen::Index configurations = (x_ind.array() == 0.0).count();
384 const Eigen::Index dimensions =
385 static_cast<Eigen::Index>(x_ind.maxCoeff());
386 Coord fit_positions;
387 if (dimensions > 0 && dimensions <= x.cols())
388 fit_positions = x.topLeftCorner(configurations, dimensions);
389 captureFittedHyperparameterDensity(fit_positions, y, theta_mode,
390 density_config, 1.0, false);
391 }
392 if (best_theta.size() == p && best_theta.allFinite() &&
393 inverse_hessian.rows() == p && inverse_hessian.cols() == p &&
394 inverse_hessian.allFinite()) {
395 inla_warm_theta_ = best_theta;
396 inla_warm_inverse_hessian_ = inverse_hessian;
397 inla_warm_valid_ = true;
398 }
399 return true;
400}
double range_at(const gpr::Coord &positions, const gpr::AtomsConfiguration &conf_info, const gpr::FieldMatrixd &lengthscale)
Definition Distance.cpp:533
double evaluateEnergy(const Eigen::VectorXd &w, const EigenMatrix &x, const Eigen::VectorXd &x_ind, const Eigen::VectorXd &y)
void setParameters(const GPRSetup &parameters)
Set parameters of the GPR model.
bool wallClockLimitReached() const
Collective on the model's process group for distributed fitters.
void captureFittedHyperparameterDensity(const Coord &positions, const Eigen::VectorXd &targets, const Eigen::VectorXd &theta, const funcmin::MapObjectiveConfig &penalty, double target_scale, bool use_ties)
double inlaMinimumLengthScale(double range_x) const
Definition INLA.cpp:142
std::unique_ptr< DLManagedTensorVersioned, RgminTensorDeleter > RgminTensorHandle
void requireCompatibleLibrary()
Definition RgminAbi.h:90
double barrier_strength
Already capped with min(current_barrier_strength, 0.5) by the caller.
gpr::MapPriorWeightMode weight_mode

◆ computeInlaPosteriorModeForTesting()

bool gpr::GaussianProcessRegression::computeInlaPosteriorModeForTesting ( const EigenMatrix & x,
const Eigen::VectorXd & x_ind,
const Eigen::VectorXd & y,
Eigen::VectorXd & theta_mode,
const TrainingKernelGeometry * training_geom )
inlinenodiscard

Definition at line 3052 of file GaussianProcessRegression.h.

3056 {
3057 return computeInlaPosteriorMode(x, x_ind, y, theta_mode, training_geom);
3058 }
bool computeInlaPosteriorMode(const EigenMatrix &x, const Eigen::VectorXd &x_ind, const Eigen::VectorXd &y, Eigen::VectorXd &theta_mode, const TrainingKernelGeometry *training_geom)
Definition INLA.cpp:234

◆ computeLaplaceSkipScgShiftNorm()

double gpr::GaussianProcessRegression::computeLaplaceSkipScgShiftNorm ( const EigenMatrix & opt_R_matrix,
const Eigen::VectorXd & opt_R_indices,
const Eigen::VectorXd & opt_y )
nodiscard

Compatibility wrapper for the Laplace skip-SCG API. Uses the current covariance-function parameter vector as the reference point.

Definition at line 3819 of file Optimize.cpp.

3822{
3823 const Eigen::VectorXd theta_reference =
3824 sexpat_cov_func ? sexpat_cov_func->combineParameters()
3825 : Eigen::VectorXd{};
3826 return computeObjectiveStationarityShiftNorm(opt_R_matrix, opt_R_indices,
3827 opt_y, theta_reference);
3828}
double computeObjectiveStationarityShiftNorm(const EigenMatrix &opt_R_matrix, const Eigen::VectorXd &opt_R_indices, const Eigen::VectorXd &opt_y, const Eigen::VectorXd &theta_reference, Eigen::VectorXd *shift_out=nullptr, double *energy_out=nullptr, Eigen::VectorXd *gradient_out=nullptr)

◆ computeObjectiveStationarityShiftNorm()

double gpr::GaussianProcessRegression::computeObjectiveStationarityShiftNorm ( const EigenMatrix & opt_R_matrix,
const Eigen::VectorXd & opt_R_indices,
const Eigen::VectorXd & opt_y,
const Eigen::VectorXd & theta_reference,
Eigen::VectorXd * shift_out = nullptr,
double * energy_out = nullptr,
Eigen::VectorXd * gradient_out = nullptr )
nodiscard

Definition at line 3700 of file Optimize.cpp.

3705{
3706 if (sexpat_cov_func == nullptr || lik_gaussian == nullptr) {
3707 return std::numeric_limits<double>::infinity();
3708 }
3709 if (theta_reference.size() == 0) {
3710 return std::numeric_limits<double>::infinity();
3711 }
3712
3713 // The predicate consumes the Euclidean predicted-shift norm
3714 // ||H^{-1} g_new||_2.
3715 // Laplace stores L with H^{-1} = L L^T. Slice/PSIS and MAP/SCG store U
3716 // with H = U^T U.
3717 const Eigen::MatrixXd* L_posterior = nullptr;
3718 const Eigen::MatrixXd* U_hessian = nullptr;
3719 const Eigen::MatrixXd* H_inverse = nullptr;
3720 if (laplace_posterior_ && laplace_posterior_->valid) {
3721 const Eigen::MatrixXd& L_p = laplace_posterior_->laplace.lScale();
3722 if (L_p.size() > 0) {
3723 L_posterior = &L_p;
3724 }
3725 }
3726 if (L_posterior == nullptr && slice_laplace_state_ &&
3727 slice_laplace_state_->valid &&
3728 slice_laplace_state_->hessian_chol_U.size() > 0) {
3729 U_hessian = &slice_laplace_state_->hessian_chol_U;
3730 }
3731 if (L_posterior == nullptr && U_hessian == nullptr &&
3732 objective_stationarity_hessian_valid_ &&
3733 objective_stationarity_hessian_chol_U_.rows() ==
3734 theta_reference.size()) {
3735 U_hessian = &objective_stationarity_hessian_chol_U_;
3736 }
3737 if (L_posterior == nullptr && U_hessian == nullptr &&
3738 objective_stationarity_inverse_hessian_valid_ &&
3739 objective_stationarity_inverse_hessian_.rows() ==
3740 theta_reference.size()) {
3741 H_inverse = &objective_stationarity_inverse_hessian_;
3742 }
3743 const bool use_bb_scalar =
3744 L_posterior == nullptr && U_hessian == nullptr &&
3745 H_inverse == nullptr && objective_stationarity_bb_valid_ &&
3746 objective_stationarity_bb_dimension_ == theta_reference.size() &&
3747 objective_stationarity_bb_inverse_scale_ > 0.0 &&
3748 std::isfinite(objective_stationarity_bb_inverse_scale_);
3749 last_stationarity_model_ = L_posterior != nullptr ? 1
3750 : U_hessian != nullptr ? 2
3751 : H_inverse != nullptr ? 3
3752 : use_bb_scalar ? 4
3753 : 0;
3754 if (L_posterior == nullptr && U_hessian == nullptr &&
3755 H_inverse == nullptr && !use_bb_scalar) {
3756 return std::numeric_limits<double>::infinity();
3757 }
3758
3759 double energy_buf = 0.0;
3760 Eigen::VectorXd grad_buf = Eigen::VectorXd::Zero(theta_reference.size());
3761 EnergyAndGradient eg(energy_buf, grad_buf);
3762 // The marginal likelihood at the reference goes through the fit's
3763 // cached training geometry, the same route as the optimizer's own
3764 // evaluations; the live block walk it replaced cost 11_grignard a
3765 // sixth of its band wall at one evaluation per outer.
3766 bool device_objective = false;
3767#ifdef GPR_LINALG_KOKKOS
3768 device_objective = canUseDevicePosterior();
3769#endif
3770 const TrainingKernelGeometry* reference_geometry =
3771 hyperparameter_objective_mode_ == HyperparameterObjectiveMode::NLML &&
3773 use_training_geometry_handle_ && !device_objective
3774 ? fitGeometryFor(opt_R_matrix, opt_R_indices)
3775 : nullptr;
3776 if (reference_geometry != nullptr) {
3778 *reference_geometry, opt_R_matrix,
3779 opt_R_indices, opt_y, eg);
3780 } else {
3782 theta_reference, opt_R_matrix, opt_R_indices, opt_y, eg);
3783 }
3784 const Eigen::Index hdim =
3785 L_posterior != nullptr
3786 ? L_posterior->rows()
3787 : (U_hessian != nullptr
3788 ? U_hessian->rows()
3789 : (H_inverse != nullptr
3790 ? H_inverse->rows()
3791 : objective_stationarity_bb_dimension_));
3792 if (!std::isfinite(energy_buf) || grad_buf.size() != hdim ||
3793 !grad_buf.allFinite()) {
3794 return std::numeric_limits<double>::infinity();
3795 }
3796
3797 if (energy_out != nullptr) *energy_out = energy_buf;
3798 if (gradient_out != nullptr) *gradient_out = grad_buf;
3799 Eigen::VectorXd v;
3800 if (L_posterior != nullptr) {
3801 v = (*L_posterior) * (L_posterior->transpose() * grad_buf);
3802 } else if (U_hessian != nullptr) {
3803 const Eigen::VectorXd rhs = U_hessian->transpose()
3804 .template triangularView<Eigen::Lower>()
3805 .solve(grad_buf);
3806 v = U_hessian->template triangularView<Eigen::Upper>().solve(rhs);
3807 } else if (H_inverse != nullptr) {
3808 v = (*H_inverse) * grad_buf;
3809 } else {
3810 if (shift_out != nullptr) {
3811 *shift_out = objective_stationarity_bb_inverse_scale_ * grad_buf;
3812 }
3813 return objective_stationarity_bb_inverse_scale_ * grad_buf.norm();
3814 }
3815 if (shift_out != nullptr) *shift_out = v;
3816 return v.norm();
3817}
bool canUseTrainingGeometryObjective() const noexcept
Definition Optimize.cpp:389
void evaluateEnergyAndGradientFromGeometry(const Eigen::VectorXd &w, const TrainingKernelGeometry &geom, const EigenMatrix &x, const Eigen::VectorXd &x_ind, const Eigen::VectorXd &y, EnergyAndGradient &energy_and_gradient)
void evaluateHyperparameterObjectiveEnergyAndGradient(const Eigen::VectorXd &w, const EigenMatrix &x, const Eigen::VectorXd &x_ind, const Eigen::VectorXd &y, EnergyAndGradient &energy_and_gradient)
const TrainingKernelGeometry * fitGeometryFor(const EigenMatrix &x, const Eigen::VectorXd &x_ind) const

◆ computePairtypeDescriptorScale()

bool gpr::GaussianProcessRegression::computePairtypeDescriptorScale ( const Coord & R,
const AtomsConfiguration & conf_info,
Eigen::VectorXd & ls_k )
staticprotected

Per-pairtype motion scale rho0_k = sqrt(sum_f var(1/r_f)). Each pair feature is centered across configurations before summing its variance within InverseDistanceDescriptor::featurePairtypes groups. Units are inverse Angstrom. These scales seed SExpAt and anchor the MAP length-scale prior (MapObjectiveConfig::lengthscale_rho0).

Returns
true when every group has positive finite motion. Static groups retain zero in ls_k, so callers can supply chemical scales per group. Empty input leaves ls_k unchanged; invalid features clear it.

Definition at line 1351 of file GaussianProcessRegression.cpp.

1353{
1354 return InverseDistanceDescriptor::pairtypeMotionScales(R, conf_info, ls_k);
1355}
static bool pairtypeMotionScales(const Coord &positions, const AtomsConfiguration &configuration, Eigen::VectorXd &scales)

◆ conditionActivePosterior()

bool gpr::GaussianProcessRegression::conditionActivePosterior ( const Observation & full_observation,
std::shared_ptr< const KernelOperator > active_kernel = {} )
nodiscard

Condition the fitted full GP plus an independent active kernel on the appended rows of a cumulative observation history. The full-fit prefix must match exactly. Each call conditions on that suffix once, using the same frozen background. A null kernel gives sequential conditioning. Kernel outputs use physical energy-gradient covariance units.

Definition at line 1147 of file ActivePosterior.cpp.

1150{
1151 auto state = prepareActivePosterior(full_observation);
1152 if (!state) return false;
1153 const Eigen::Index n = state->posterior.channels();
1154 EigenMatrix active = EigenMatrix::Zero(n, n);
1155 if (active_kernel)
1156 active =
1157 active_kernel->jointEnergyGradientCovariance(state->observations.R);
1158 if (!state->posterior.condition(active)) return false;
1159 state->kernel = std::move(active_kernel);
1160 state->includes_pair = false;
1161 state->kernel_name = state->kernel ? "fixed" : "background";
1162 prepareActivePosteriorMeanExpansion(*state);
1163 active_posterior_ = std::move(state);
1164 advanceActivePosteriorEpoch();
1165 return true;
1166}

◆ conditionDevicePosterior()

std::optional< double > gpr::GaussianProcessRegression::conditionDevicePosterior ( const EigenMatrix & rows,
const Eigen::VectorXd & indices,
const Eigen::VectorXd & targets,
bool placeholder_targets = false )
protected

Definition at line 298 of file DevicePosterior.cpp.

300{
301 return std::nullopt;
302}

◆ conditionOnHyperparameterPosterior()

bool gpr::GaussianProcessRegression::conditionOnHyperparameterPosterior ( const HyperparameterPosterior & posterior)
nodiscard

Condition the quadrature on this model's rows without reweighting its hyperparameters by a likelihood already represented by the source. Requires the same parameter point, output units, noise and pair types. A charted kernel can restore its own quadrature but cannot transfer it to another model. Factors are built on the first integrated prediction. False leaves the current posterior unchanged.

Definition at line 166 of file HyperparameterPosterior.cpp.

168{
169 if (!hyperparameterPosteriorCompatible(posterior)) return false;
170 pending_hyperparameter_posterior_ = posterior;
171 laplace_posterior_.reset();
172 ++laplace_model_revision_;
173 return true;
174}

◆ configureLengthScaleTies()

void gpr::GaussianProcessRegression::configureLengthScaleTies ( const AtomsConfiguration & configuration)

Definition at line 693 of file GaussianProcessRegression.cpp.

695{
696 length_scale_ties_ = LengthScaleTies{};
697 if (sexpat_cov_func != nullptr)
698 sexpat_cov_func->setLengthScalePriorWeights(Eigen::VectorXd());
699 const auto& parent = configuration.pair_type_parent;
700 if (configuration.n_base_pt == 0 || parent.empty() ||
701 static_cast<Index_t>(parent.size()) != configuration.n_pt)
702 return;
703 for (const auto base: parent)
704 if (base >= configuration.n_base_pt) return;
705 length_scale_ties_.parent = parent;
706 length_scale_ties_.released.assign(parent.size(), false);
707 length_scale_ties_.evidence.assign(parent.size(), 0.0);
708 length_scale_ties_.base_count = configuration.n_base_pt;
709 length_scale_ties_.valid = true;
711}
void refreshLengthScaleLeaders()
Recomputes the leaders from the released flags.

◆ configureMinimumModeRefit()

bool gpr::GaussianProcessRegression::configureMinimumModeRefit ( const Observation & oracle,
double force_tolerance,
ConvergenceNormType force_norm = ConvergenceNormType::L2_NORM,
const RefitTrustReport * trust_report = nullptr )

Select the active lengths using the lowest eigenvector of the Cartesian mean Hessian at the least trusted acquired observation. Every acquired row must satisfy the force uncertainty and error tolerances; any untrusted row requests a full fit. One Hessian is formed for a trusted batch, at its maximum uncertainty/error witness. The maximum-atom RMS is sqrt(max_a trace(Cov(F_a))).

Definition at line 1876 of file Optimize.cpp.

1879{
1881 if (atomic_environment_model_) return false;
1882 scg_opt_settings.active_parameters =
1883 fullRefitMask(sexpat_cov_func.get(), lik_gaussian.get());
1884 double force_sd = 0.0, force_error = 0.0;
1885 if (!active_posterior_refits_ || !(force_tolerance > 0.0) ||
1886 !std::isfinite(force_tolerance) || oracle.R.rows() <= 0 ||
1887 oracle.G.rows() != oracle.R.rows() ||
1888 oracle.G.cols() != oracle.R.cols()) {
1889 mode_refit_policy_.reset();
1890 return false;
1891 }
1892 const auto* measured_trust =
1893 trust_report && trust_report->state_ &&
1894 trust_report->state_->matches(*this, oracle, force_norm)
1895 ? trust_report->state_.get()
1896 : nullptr;
1897 Observation witness;
1898 double worst_trust = -1.0;
1899 bool overconfident = false;
1900 bool full_length_fit = false;
1901 bool component_contradiction = false;
1902 for (Eigen::Index row = 0; row < oracle.R.rows(); ++row) {
1903 Observation measured;
1904 measured.R = oracle.R.middleRows(row, 1);
1905 measured.G = oracle.G.middleRows(row, 1);
1906 double row_sd = 0.0, row_error = 0.0;
1907 bool eligible = true;
1908 if (measured_trust) {
1909 const auto& row_trust = measured_trust->rows[row];
1910 row_sd = row_trust.force_sd;
1911 row_error = row_trust.force_error;
1912 } else {
1913 eligible =
1914 measureModeRefitTrust(measured, row_sd, row_error, force_norm);
1915 }
1916 if (!eligible) {
1917 if (report_level >= 1)
1918 log_man << "Minimum-mode refit: full fit, acquired row " << row
1919 << "/" << oracle.R.rows() << ", eligible " << eligible
1920 << ", fitted " << has_been_optimized_ << ", decomposed "
1921 << is_decomposed_succesfully << ", force uncertainty "
1922 << row_sd << ", measured force error " << row_error
1923 << "\n";
1924 mode_refit_policy_.reset();
1925 return false;
1926 }
1927 full_length_fit = full_length_fit || row_sd >= force_tolerance;
1928 component_contradiction =
1929 component_contradiction ||
1930 ((environment_residuals_ || additive_pair_residuals_) &&
1931 row_error > row_sd);
1932 overconfident = overconfident || row_error >= force_tolerance;
1933 // A measured force error at the tolerance is evidence against the
1934 // surrogate's hyperparameters: the next full fit's anneal stage.
1935 if (row_error >= force_tolerance) surrogate_contradicted_ = true;
1936 force_sd = std::max(force_sd, row_sd);
1937 force_error = std::max(force_error, row_error);
1938 const double trust = std::max(row_sd, row_error);
1939 if (trust > worst_trust) {
1940 worst_trust = trust;
1941 witness = std::move(measured);
1942 }
1943 }
1944 if (active_posterior_ && overconfident) {
1945 // The measured contradiction is against the combined posterior.
1946 // Refitting only its conditional correction keeps the background
1947 // fixed at its anchors and cannot reassess that part of the model.
1948 mode_refit_policy_.reset();
1949 if (report_level >= 1)
1950 log_man << "Minimum-mode refit: full fit of contradicted combined "
1951 "posterior, force uncertainty "
1952 << force_sd << ", measured force error " << force_error
1953 << "\n";
1954 return false;
1955 }
1956 if (full_length_fit) {
1957 // Any acquired contradiction can require a richer kernel, even
1958 // when another acquired row has high, calibrated uncertainty.
1959 // All residual length scales vary; candidate evidence decides
1960 // whether to retain the background and adopt the correction.
1961 residual_model_refit_ = component_contradiction;
1962 if (report_level >= 1)
1963 log_man << "Minimum-mode refit: "
1964 << (residual_model_refit_ ? "residual model fit"
1965 : "full fit")
1966 << ", acquired rows " << oracle.R.rows()
1967 << ", force uncertainty " << force_sd
1968 << ", measured force error " << force_error << "\n";
1969 mode_refit_policy_.reset();
1970 return false;
1971 }
1972 if (overconfident) {
1973 residual_model_refit_ = true;
1974 if (report_level >= 1)
1975 log_man << "Residual model refit: " << oracle.R.rows()
1976 << " measured rows, force uncertainty " << force_sd
1977 << ", measured force error " << force_error
1978 << ", residual variance from the sparse posterior ("
1979 << last_residual_inducing_count_ << " inducing of "
1980 << last_residual_configuration_count_
1981 << " configurations in the last fit, exact per "
1982 "configuration)\n";
1983 mode_refit_policy_.reset();
1984 return false;
1985 }
1986 const Eigen::Index dof = oracle.R.cols();
1987 EigenMatrix hessian;
1989 if (prepareMeanHessianVectorHssvd(witness.R, prepared)) {
1991 prepared, EigenMatrix::Identity(dof, dof), hessian)) {
1992 // The prepared block owns the curvature. A failed apply is a
1993 // refusal: the exact kernel and the stencil are not matrices
1994 // this refit may diagonalize.
1995 mode_refit_policy_.reset();
1996 return false;
1997 }
1998 } else {
1999 hessian.resize(dof, dof);
2000 const auto mean_hessian = prepareMeanHessian(witness.R);
2001 if (!mean_hessian) {
2002 mode_refit_policy_.reset();
2003 return false;
2004 }
2005 for (Eigen::Index column = 0; column < dof; ++column) {
2006 Eigen::VectorXd action;
2007 if (!mean_hessian(Eigen::VectorXd::Unit(dof, column), action)) {
2008 mode_refit_policy_.reset();
2009 return false;
2010 }
2011 hessian.col(column) = action;
2012 }
2013 }
2014 hessian = 0.5 * (hessian + hessian.transpose()).eval();
2015 Eigen::SelfAdjointEigenSolver<EigenMatrix> modes(hessian);
2016 if (modes.info() != Eigen::Success || !modes.eigenvalues().allFinite() ||
2017 modes.eigenvalues()(0) >=
2018 -std::sqrt(std::numeric_limits<double>::epsilon()) *
2019 hessian.norm()) {
2020 mode_refit_policy_.reset();
2021 return false;
2022 }
2023 const Coord mode = modes.eigenvectors().col(0).transpose();
2024 return selectModeRefit(witness, mode, force_tolerance, force_sd,
2025 force_error);
2026}
Half measured(const GradientOracle &oracle, const Eigen::VectorXd &x, Kind kind, const Options &options)
Full central difference of the oracle gradient: 2 d calls.

◆ configureModeRefit()

bool gpr::GaussianProcessRegression::configureModeRefit ( const Observation & oracle,
const Coord & mode,
double force_tolerance,
ConvergenceNormType force_norm = ConvergenceNormType::L2_NORM )

Restrict one refit using a minimum-mode estimate and an oracle force. Uncertain predictions and measured force errors request the full fit. Error and marginal force RMS use the caller's convergence norm.

Definition at line 1745 of file Optimize.cpp.

1748{
1750 if (atomic_environment_model_) return false;
1751 // A rejected active fit releases every parameter. An empty mask lets
1752 // the automatic identifiability policy hold length scales instead.
1753 scg_opt_settings.active_parameters =
1754 fullRefitMask(sexpat_cov_func.get(), lik_gaussian.get());
1755 double force_error = 0.0, force_sd = 0.0;
1756 if (mode.rows() != 1 || mode.cols() != oracle.R.cols() ||
1757 !measureModeRefitTrust(oracle, force_sd, force_error, force_norm)) {
1758 mode_refit_policy_.reset();
1759 return false;
1760 }
1761 return selectModeRefit(oracle, mode, force_tolerance, force_sd,
1762 force_error);
1763}

◆ contractActiveCovarianceDerivatives()

bool gpr::GaussianProcessRegression::contractActiveCovarianceDerivatives ( const TrainingKernelGeometry & geom,
const Eigen::VectorXd & x_ind,
const Eigen::VectorXd & theta,
const std::vector< bool > & active_lengths,
const EigenMatrix & weight,
const std::vector< Eigen::Index > & derivative_lengths,
Eigen::VectorXd & contractions,
bool serial_per_rank = false )
nodiscard

Frobenius products with latent active-kernel parameter derivatives. Returns amplitude followed by the requested log lengths. Block owners reduce scalar products without storing full derivative matrices.

Definition at line 2050 of file CovarianceAssembly.cpp.

2056{
2057 contractions.resize(0);
2058 Eigen::VectorXd active_theta;
2059 if (!geom.valid || geom.n <= 0 || geom.n != x_ind.size() ||
2060 !x_ind.allFinite() || weight.rows() != geom.n ||
2061 weight.cols() != geom.n || !weight.allFinite() ||
2062 !activeLogParameters(sexpat_cov_func.get(), theta, active_lengths,
2063 derivative_lengths, active_theta))
2064 return false;
2065 EigenMatrix unused;
2066 if (!assembleSexpatCovFromGeometry(
2067 *this, backend(), geom, *sexpat_cov_func, x_ind, unused,
2068 /*do_reduce=*/true, serial_per_rank, &active_theta, nullptr,
2069 &derivative_lengths, &weight, &contractions)) {
2070 contractions.resize(0);
2071 return false;
2072 }
2073 return true;
2074}

◆ covarianceParameterCount()

Eigen::Index gpr::GaussianProcessRegression::covarianceParameterCount ( ) const
nodiscardprotected

Definition at line 467 of file GaussianProcessRegression.cpp.

468{
469 if (sexpat_cov_func == nullptr) return 0;
470 return 1 + sexpat_cov_func->getLengthScaleRef().size();
471}

◆ currentHyperparameterPosterior()

GaussianProcessRegression::HyperparameterPosterior gpr::GaussianProcessRegression::currentHyperparameterPosterior ( ) const
nodiscard

Retain an existing, current quadrature without estimating a new one.

Definition at line 93 of file HyperparameterPosterior.cpp.

94{
96 if (uncertainty_mode_ != UncertaintyMode::EB &&
97 uncertainty_mode_ != UncertaintyMode::LAPLACE)
98 return result;
99 if (!pending_hyperparameter_posterior_.empty() &&
100 hyperparameterPosteriorCompatible(pending_hyperparameter_posterior_))
101 return pending_hyperparameter_posterior_;
102 if (!laplace_posterior_ || !laplace_posterior_->valid ||
103 !laplace_posterior_->signature.stamp.matches(
104 currentLaplacePosteriorStamp()))
105 return result;
106 auto state = std::make_shared<HyperparameterPosterior::State>();
107 state->source = this;
108 state->mode = packInlaHyperparameters();
109 state->laplace = laplace_posterior_->laplace;
110 state->length_scales = lengthScaleFitState();
111 state->atoms = atoms_config;
112 state->kernel_atoms = sexpat_cov_func->getConfInfo();
113 state->profile = model_profile_;
114 state->mean = y_mean_;
115 state->scale = y_scale_;
116 state->likelihood_variance = likelihoodNoiseVariance();
117 state->constant_variance = const_cov_fun->getConstSigma2();
118 state->jitter_variance = jitter_sigma2;
119 state->zbl_mean = use_zbl_prior_mean_;
120 state->ff_mean = use_ff_prior_mean_;
121 state->learns_likelihood_noise = theta_includes_likelihood_noise_;
122 state->chart = sexpat_cov_func->manifoldChart();
123 state->heat = sexpat_cov_func->geodesicHeatKernel();
124 for (const auto& factor: laplace_posterior_->factors) {
125 if (factor.valid && factor.weight > 0.0)
126 state->points.push_back(factor.theta);
127 }
128 state->weights.resize(static_cast<Eigen::Index>(state->points.size()));
129 Eigen::Index index = 0;
130 for (const auto& factor: laplace_posterior_->factors) {
131 if (factor.valid && factor.weight > 0.0)
132 state->weights(index++) = factor.weight;
133 }
134 result.state_ = std::move(state);
135 return result;
136}
LengthScaleFitState lengthScaleFitState() const

◆ currentThetaIncludesLikelihoodNoise()

bool gpr::GaussianProcessRegression::currentThetaIncludesLikelihoodNoise ( ) const
nodiscardprotectednoexcept

Definition at line 480 of file GaussianProcessRegression.cpp.

482{
483 return theta_includes_likelihood_noise_;
484}

◆ decomposeCovarianceMatrix()

bool gpr::GaussianProcessRegression::decomposeCovarianceMatrix ( const EigenMatrix & x,
const Eigen::VectorXd & x_ind )
protected

Evaluate and decompose the covariance matrix using Cholesky decomposition.

Definition at line 3283 of file Decompose.cpp.

3285{
3286#ifdef GPR_LINALG_KOKKOS
3287 if (const auto value = conditionDevicePosterior(
3288 x, x_ind, Eigen::VectorXd::Zero(x.rows()), true))
3289 return std::isfinite(*value);
3290#endif
3292 // The rank-one constant kernel needs the permuted design; it is bound
3293 // once the permutation is in place below.
3294 Eigen::VectorXd factor_constant;
3295 const auto timedFactor = [&](const EigenMatrix& matrix) {
3296 ++full_cholesky_factorizations_for_testing_;
3297 ScopedPhaseTimer cholesky_timer(PhaseTimers::cholesky_seconds);
3299 backend(), matrix, factor_constant, L);
3300 if (accepted)
3302 else
3304 return accepted;
3305 };
3306#ifdef GPR_LINALG_SCALAPACK
3307 return decomposeCovarianceMatrixScalapack(x, x_ind);
3308#else
3309 EigenMatrix x_ordered = x;
3310 Eigen::VectorXd ind_ordered = x_ind;
3311 if (hasTrainingPermutation()) {
3313 ind_ordered = permuteTrainingVector(x_ind);
3314 }
3315 const Eigen::VectorXd constant_update = permuteTrainingVector(
3316 detail::constantCovarianceUpdate(const_cov_fun.get(), x_ind));
3317 const Eigen::Index n_rows = x_ordered.rows();
3318 auto invalidate_serial_signature = [&]() {
3319 serial_factor_signature_.valid = false;
3320 };
3321 auto record_serial_signature = [&]() {
3322 auto& signature = serial_factor_signature_;
3323 signature.rows = x_ordered;
3324 signature.indices = ind_ordered;
3325 signature.constant = constant_update;
3326 signature.jitter_sigma2 = jitter_sigma2;
3327 signature.nugget_coefficient = kernelNuggetCoefficient(n_rows);
3328 if (lik_gaussian != nullptr) {
3329 signature.noise = lik_gaussian->evaluateTrainingVariance(x_ordered);
3330 } else {
3331 signature.noise.resize(0);
3332 }
3333 if (sexpat_cov_func != nullptr) {
3334 signature.theta = sexpat_cov_func->combineParameters();
3335 signature.manifold_chart = sexpat_cov_func->usesManifoldChart();
3336 signature.geodesic_heat = sexpat_cov_func->usesGeodesicHeatKernel();
3337 signature.chart_identity = sexpat_cov_func->manifoldChart();
3338 signature.heat_identity = sexpat_cov_func->geodesicHeatKernel();
3339 signature.kernel_geometry = sexpat_cov_func->getConfInfo();
3340 signature.far_field_radius = sexpat_cov_func->farFieldRadius();
3341 } else {
3342 signature.theta.resize(0);
3343 signature.manifold_chart = false;
3344 signature.geodesic_heat = false;
3345 signature.chart_identity.reset();
3346 signature.heat_identity.reset();
3347 signature.kernel_geometry = AtomsConfiguration{};
3348 signature.far_field_radius = 0.0;
3349 }
3350 signature.valid = lik_gaussian != nullptr &&
3351 sexpat_cov_func != nullptr && !use_correction_ &&
3352 L.rows() == activeFactorOrder(n_rows) &&
3353 C.rows() == activeFactorOrder(n_rows);
3355 };
3356 // Fixed hyperparameters: the new permuted design is the cached one plus
3357 // k rows. Reuse the leading covariance and extend its Cholesky factor.
3358 // Woodbury on the inverse is the same block step; the factor is what
3359 // the solves store.
3360 auto try_serial_append = [&]() -> bool {
3361 auto& signature = serial_factor_signature_;
3362 const Eigen::Index n_old = signature.rows.rows();
3363 const Eigen::Index m_old = activeFactorOrder(n_old);
3364 if (!signature.valid || use_correction_ || principled_nugget_ ||
3365 signature.nugget_coefficient != 0.0 || lik_gaussian == nullptr ||
3366 sexpat_cov_func == nullptr ||
3368 return false;
3369 if (rigid_deflation_.active && rigid_deflation_.full_rows != n_old)
3370 return false;
3371 // Theta does not identify the manifold chart or the geodesic
3372 // summand. The border below is the same cross operator as a full
3373 // factor, including a geodesic summand already present in the saved
3374 // factor. A chart, or a geodesic flag that differs from that factor,
3375 // rebuilds. Immutable chart and heat-kernel identities bind the factor
3376 // to its anchor, weight, and reference path.
3377 if (sexpat_cov_func->usesManifoldChart() || signature.manifold_chart ||
3378 sexpat_cov_func->usesGeodesicHeatKernel() !=
3379 signature.geodesic_heat ||
3380 signature.heat_identity != sexpat_cov_func->geodesicHeatKernel())
3381 return false;
3382 // factor_epoch_ counts a fitted posterior, not an objective
3383 // evaluation that borrows C and L. Geometry identity, including the
3384 // active type count, is detail::sameSexpatGeometry.
3385 if (!detail::sameSexpatGeometry(
3386 signature.kernel_geometry, sexpat_cov_func->getConfInfo(),
3387 signature.far_field_radius, sexpat_cov_func->farFieldRadius()))
3388 return false;
3389 if (n_old <= 0 || m_old <= 0 || n_rows <= n_old || L.rows() != m_old ||
3390 L.cols() != m_old || C.rows() != m_old || C.cols() != m_old)
3391 return false;
3392 if (signature.jitter_sigma2 != jitter_sigma2) return false;
3393 if (signature.rows.cols() != x_ordered.cols() ||
3394 signature.indices.size() != n_old ||
3395 signature.constant.size() != n_old ||
3396 signature.noise.size() != n_old || signature.theta.size() == 0)
3397 return false;
3398 if (!(x_ordered.topRows(n_old).array() == signature.rows.array())
3399 .all() ||
3400 !(ind_ordered.head(n_old).array() == signature.indices.array())
3401 .all() ||
3402 !(constant_update.head(n_old).array() == signature.constant.array())
3403 .all() ||
3404 signature.theta != sexpat_cov_func->combineParameters())
3405 return false;
3406 const Eigen::VectorXd noise_now =
3407 lik_gaussian->evaluateTrainingVariance(x_ordered);
3408 if (noise_now.size() != n_rows ||
3409 !(noise_now.head(n_old).array() == signature.noise.array()).all())
3410 return false;
3411
3412 const Eigen::Index k = n_rows - n_old;
3413 const EigenMatrix x_new = x_ordered.bottomRows(k);
3414 const Eigen::VectorXd ind_new = ind_ordered.tail(k);
3415 // Cross-covariance assembly consumes contiguous channel blocks;
3416 // the cached factor orders every geometry's channels together.
3417 const auto new_groups = buildStructuredPermutation(ind_new);
3418 const auto all_groups = buildStructuredPermutation(ind_ordered);
3419 const EigenMatrix x_new_grouped = permuteMatrixRows(x_new, new_groups);
3420 const EigenMatrix x_all_grouped =
3421 permuteMatrixRows(x_ordered, all_groups);
3422 const Eigen::VectorXd ind_new_grouped =
3423 permuteVector(ind_new, new_groups);
3424 const Eigen::VectorXd ind_all_grouped =
3425 permuteVector(ind_ordered, all_groups);
3426 Eigen::VectorXd u_new, u_all;
3427 extractUniqueIndices(ind_new_grouped, u_new);
3428 extractUniqueIndices(ind_all_grouped, u_all);
3429 EigenMatrix grouped_kernel;
3430 applyCrossCovarianceFunction(x_new_grouped, x_all_grouped,
3431 ind_new_grouped, u_new, ind_all_grouped,
3432 u_all, *sexpat_cov_func, grouped_kernel,
3433 /*do_reduce=*/false);
3434 if (grouped_kernel.rows() != k || grouped_kernel.cols() != n_rows ||
3435 !grouped_kernel.allFinite())
3436 return false;
3437 EigenMatrix kernel(k, n_rows);
3438 for (Eigen::Index col = 0; col < n_rows; ++col)
3439 for (Eigen::Index row = 0; row < k; ++row)
3440 kernel(new_groups.perm[row], all_groups.perm[col]) =
3441 grouped_kernel(row, col);
3442 grouped_kernel.resize(0, 0);
3443 kernel += constant_update.tail(k) * constant_update.transpose();
3444
3445 EigenMatrix left_block;
3446 EigenMatrix right_block;
3447 detail::RigidDeflationState tail_state;
3448 RigidDeflationDiagnostic tail_diag;
3449 if (rigid_deflation_.active) {
3450 const AtomsConfiguration& effective_conf =
3451 sexpat_cov_func->getConfInfo().atoms_mov.type.size() > 0
3452 ? sexpat_cov_func->getConfInfo()
3453 : atoms_config;
3454 if (!detail::prepareRigidDeflationState(
3455 use_rigid_null_deflation_, /*factor_order=*/true,
3456 effective_conf, x_new, ind_new, noise_now.tail(k),
3457 jitter_sigma2, /*unsupported=*/false, tail_state,
3458 tail_diag))
3459 return false;
3460 EigenMatrix right_raw = kernel.rightCols(k);
3461 if (!detail::verifySignalKernelRigidNullspace(right_raw, tail_state,
3462 tail_diag))
3463 return false;
3464 EigenMatrix left_raw = kernel.leftCols(n_old);
3465 if (!detail::verifyCrossBlockRigidNullspace(
3466 left_raw, tail_state, rigid_deflation_, tail_diag))
3467 return false;
3468 left_block = tail_state.projectRows(left_raw);
3469 left_block = rigid_deflation_.projectRows(left_block.transpose())
3470 .transpose();
3471 right_block = tail_state.projectSymmetric(right_raw);
3472 for (Eigen::Index i = 0; i < tail_state.num_geometries; ++i) {
3473 const auto& blk =
3474 tail_state.blocks[static_cast<std::size_t>(i)];
3475 right_block(blk.deflated_row_offset, blk.deflated_row_offset) +=
3476 noise_now(n_old + blk.full_row_offset) + jitter_sigma2;
3477 if (blk.deflated_grad_dim > 0) {
3478 right_block.diagonal()
3479 .segment(blk.deflated_row_offset + 1,
3480 blk.deflated_grad_dim)
3481 .array() += blk.grad_noise_variance;
3482 }
3483 }
3484 } else {
3485 kernel.rightCols(k).diagonal() += noise_now.tail(k);
3486 if (jitter_sigma2 > 0.0)
3487 kernel.rightCols(k).diagonal().array() += jitter_sigma2;
3488 left_block = kernel.leftCols(n_old);
3489 right_block = kernel.rightCols(k);
3490 }
3491
3492 const Eigen::Index k_eff = right_block.rows();
3493 Eigen::MatrixXd border_old = left_block.transpose();
3494 L.triangularView<Eigen::Lower>().solveInPlace(border_old);
3495 Eigen::MatrixXd schur(k_eff, k_eff);
3496 // A constant energy covariance can dwarf the conditional variance.
3497 // Accumulate the small Schur block at wider precision so cancellation
3498 // does not discard the likelihood noise. The large triangular solve
3499 // retains the backend's dense arithmetic and no wider matrix is kept.
3500 for (Eigen::Index col = 0; col < k_eff; ++col) {
3501 for (Eigen::Index row = col; row < k_eff; ++row) {
3502 long double value =
3503 0.5L * (static_cast<long double>(right_block(row, col)) +
3504 static_cast<long double>(right_block(col, row)));
3505 for (Eigen::Index i = 0; i < m_old; ++i)
3506 value -= static_cast<long double>(border_old(i, row)) *
3507 static_cast<long double>(border_old(i, col));
3508 schur(row, col) = schur(col, row) = static_cast<double>(value);
3509 }
3510 }
3511 Eigen::LLT<Eigen::MatrixXd> schur_factor(schur);
3512 if (schur_factor.info() != Eigen::Success) return false;
3513
3514 const Eigen::Index m_new = m_old + k_eff;
3515 EigenMatrix factor = EigenMatrix::Zero(m_new, m_new);
3516 factor.topLeftCorner(m_old, m_old) = L;
3517 factor.bottomLeftCorner(k_eff, m_old) = border_old.transpose();
3518 factor.bottomRightCorner(k_eff, k_eff) = schur_factor.matrixL();
3519 signature.valid = false;
3520 L = std::move(factor);
3522 EigenMatrix covariance = EigenMatrix::Zero(m_new, m_new);
3523 covariance.topLeftCorner(m_old, m_old) = C;
3524 covariance.bottomLeftCorner(k_eff, m_old) = left_block;
3525 covariance.topRightCorner(m_old, k_eff) = left_block.transpose();
3526 covariance.bottomRightCorner(k_eff, k_eff) = right_block;
3527 C = std::move(covariance);
3528 if (rigid_deflation_.active) {
3529 for (auto blk: tail_state.blocks) {
3530 blk.full_row_offset += n_old;
3531 blk.deflated_row_offset += m_old;
3532 rigid_deflation_.blocks.push_back(std::move(blk));
3533 }
3534 rigid_deflation_.full_rows = n_rows;
3535 rigid_deflation_.deflated_rows = m_new;
3536 rigid_deflation_.num_geometries += tail_state.num_geometries;
3537 rigid_deflation_diag_.full_rows = n_rows;
3538 rigid_deflation_diag_.deflated_rows = m_new;
3539 rigid_deflation_diag_.geometries = rigid_deflation_.num_geometries;
3540 rigid_deflation_diag_.rigid_modes += tail_diag.rigid_modes;
3541 rigid_deflation_diag_.kernel_null_norm =
3542 std::max(rigid_deflation_diag_.kernel_null_norm,
3543 tail_diag.kernel_null_norm);
3544 rigid_deflation_diag_.kernel_relative_null_norm =
3545 std::max(rigid_deflation_diag_.kernel_relative_null_norm,
3546 tail_diag.kernel_relative_null_norm);
3547 rigid_deflation_diag_.kernel_schur_null_error =
3548 std::max(rigid_deflation_diag_.kernel_schur_null_error,
3549 tail_diag.kernel_schur_null_error);
3550 rigid_deflation_diag_.kernel_relative_schur_null_error =
3551 std::max(rigid_deflation_diag_.kernel_relative_schur_null_error,
3552 tail_diag.kernel_relative_schur_null_error);
3553 rigid_deflation_diag_.applied = true;
3554 rigid_deflation_diag_.reason =
3555 (rigid_deflation_diag_.reason == "deflated_exact" &&
3556 tail_diag.reason == "deflated_exact")
3557 ? "deflated_exact"
3558 : "deflated_projected";
3560 } else {
3561 extendTrainingInverseDiagonal(m_old, m_new);
3562 }
3564 ++incremental_cholesky_updates_for_testing_;
3565 record_serial_signature();
3566 return signature.valid;
3567 };
3568 if (reuseSerialFactorIfCurrent(x_ordered, ind_ordered, constant_update))
3569 return true;
3570 if (try_serial_append()) return true;
3571 if (require_factor_append_) return false;
3573
3574 // Assemble C and apply every configured diagonal regularisation. Factored
3575 // out so the rescue path below rebuilds the same operator: rebuilding with
3576 // only the escalating jitter would drop the conditioning bound the
3577 // principled nugget exists to enforce, on exactly the matrices that just
3578 // failed to factorise.
3579 const bool can_attempt_deflation =
3581 sexpat_cov_func != nullptr && lik_gaussian != nullptr &&
3582 !sexpat_cov_func->usesManifoldChart() &&
3583 !sexpat_cov_func->usesGeodesicHeatKernel() && !principled_nugget_;
3584 const Eigen::VectorXd noise_ordered =
3585 lik_gaussian != nullptr
3586 ? lik_gaussian->evaluateTrainingVariance(x_ordered)
3587 : Eigen::VectorXd::Zero(n_rows);
3588 const auto assemble_regularized_C = [&](double extra_jitter) {
3590 x, x_ind, C, /*include_noise=*/!can_attempt_deflation)) {
3592 x, x_ind, C,
3593 /*serial_per_rank=*/false,
3594 /*include_constant=*/false,
3595 /*include_noise=*/!can_attempt_deflation);
3598 }
3599 if (!can_attempt_deflation) {
3600 if (jitter_sigma2 > 0.) C.diagonal().array() += jitter_sigma2;
3601 if (use_correction_) {
3602 double K_sum =
3603 C.diagonal().sum() + constant_update.squaredNorm();
3604 Eigen::Index n = C.rows();
3605 double denom =
3606 1.0 / correction_eps_ - static_cast<double>(n * n);
3607 if (std::abs(denom) > 1e-30) {
3608 double corr = K_sum * K_sum / denom;
3609 C.diagonal().array() += corr;
3610 }
3611 }
3612 if (extra_jitter > 0.) C.diagonal().array() += extra_jitter;
3613 (void)detail::prepareRigidDeflationState(
3614 use_rigid_null_deflation_, /*factor_order=*/true, atoms_config,
3615 x_ordered, ind_ordered, noise_ordered, jitter_sigma2,
3616 /*unsupported_kernel_or_likelihood=*/true, rigid_deflation_,
3618 rigid_deflation_.reset();
3619 factor_constant = constant_update;
3620 return;
3621 }
3622 double corr = 0.0;
3623 if (use_correction_) {
3624 const double K_sum = C.diagonal().sum() + noise_ordered.sum() +
3625 static_cast<double>(n_rows) * jitter_sigma2 +
3626 constant_update.squaredNorm();
3627 const Eigen::Index n = C.rows();
3628 const double denom =
3629 1.0 / correction_eps_ - static_cast<double>(n * n);
3630 if (std::abs(denom) > 1e-30) corr = K_sum * K_sum / denom;
3631 }
3632 const double extra_uniform = jitter_sigma2 + corr + extra_jitter;
3634 x_ordered, ind_ordered, noise_ordered, extra_uniform, C,
3635 constant_update, factor_constant, /*factor_order=*/true)) {
3636 C.diagonal() += noise_ordered;
3637 if (extra_uniform != 0.0) C.diagonal().array() += extra_uniform;
3638 factor_constant = constant_update;
3639 }
3640 };
3641
3642 rigid_deflation_.reset();
3643 assemble_regularized_C(0.);
3644
3645 const auto factor_covariance = [&](const EigenMatrix& matrix) {
3646 return timedFactor(matrix);
3647 };
3648 if (detail::factorCovarianceOrSymmetricPart(C, factor_covariance)) {
3649 C.noalias() += factor_constant * factor_constant.transpose();
3650 record_serial_signature();
3651 return true;
3652 }
3653
3654 // Cholesky failed: the covariance matrix is not positive definite.
3655 // This can happen at higher optimization levels (-O2/-O3) due to
3656 // floating-point rounding in the kernel evaluation. Retry with
3657 // progressively larger jitter as a numerical safeguard.
3658 double rescue_jitter = std::max(jitter_sigma2, 1e-10);
3659 for (int attempt = 0; attempt < 5; ++attempt) {
3660 // The quiet default used to retry an indefinite factor with no
3661 // trace. The extra factorizations are the stall, when they happen.
3662 std::fprintf(stderr, "[chol-rescue] n=%lld attempt=%d jitter=%.3g\n",
3663 static_cast<long long>(C.rows()), attempt, rescue_jitter);
3664 assemble_regularized_C(rescue_jitter);
3665 if (timedFactor(C)) {
3666 C.noalias() += factor_constant * factor_constant.transpose();
3667 invalidate_serial_signature();
3668 return true;
3669 }
3670 rescue_jitter *= 10.0;
3671 }
3672 rigid_deflation_.reset();
3673 invalidate_serial_signature();
3674 return false;
3675#endif
3676}
std::optional< double > conditionDevicePosterior(const EigenMatrix &rows, const Eigen::VectorXd &indices, const Eigen::VectorXd &targets, bool placeholder_targets=false)
void extendTrainingInverseDiagonal(Eigen::Index old_order, Eigen::Index new_order)
bool evaluateTrainingCovarianceInFactorOrder(const EigenMatrix &x, const Eigen::VectorXd &x_ind, EigenMatrix &cov_matrix, bool include_noise=true)
bool tryDeflateFactorSignalCovariance(const EigenMatrix &x_ordered, const Eigen::VectorXd &ind_ordered, const Eigen::VectorXd &noise_ordered, double extra_uniform_noise, EigenMatrix &signal_cov, const Eigen::VectorXd &constant_update, Eigen::VectorXd &factor_constant, bool factor_order=true)
RigidDeflationDiagnostic rigid_deflation_diag_
virtual bool supportsRigidNullDeflation() const noexcept
static bool factorize(BackendContext &backend, const EigenMatrix &covariance, const Eigen::VectorXd &rank_one, EigenMatrix &factor)
factor factor^T = covariance + rank_one rank_one^T.
Eigen::VectorXd permuteVector(const Eigen::VectorXd &input, const StructuredPermutation &p)
StructuredPermutation buildStructuredPermutation(const Eigen::VectorXd &ind_Ddim)
EigenMatrix permuteMatrixRows(const EigenMatrix &input, const StructuredPermutation &p)
static double cholesky_seconds

◆ decomposeForFittedTargets()

bool gpr::GaussianProcessRegression::decomposeForFittedTargets ( )
protected

Factor the fitted design at the current hyperparameters and leave the posterior weights those of the fitted targets.

A device posterior is conditioned on placeholder zero targets by decomposeCovarianceMatrix; reading its weights before the fitted targets are set would give a zero mean and a zero Hessian.

Definition at line 3272 of file Decompose.cpp.

3273{
3274 const bool decomposed = decomposeCovarianceMatrix(R_matrix, R_indices);
3275#ifdef GPR_LINALG_KOKKOS
3276 if (decomposed && hasDevicePosterior() && device_targets_placeholder_ &&
3277 energy_and_gradient.size() == R_matrix.rows())
3278 refreshPosteriorWeights(energy_and_gradient);
3279#endif
3280 return decomposed;
3281}

◆ denseResultsForTesting()

const linalg::linop::DenseResultCache & gpr::GaussianProcessRegression::denseResultsForTesting ( ) const
inlinenodiscardnoexcept

Definition at line 2613 of file GaussianProcessRegression.h.

2614 {
2615 return dense_results_;
2616 }
linalg::linop::DenseResultCache dense_results_

◆ denseVariancePanelForTesting()

bool gpr::GaussianProcessRegression::denseVariancePanelForTesting ( const EigenMatrix & positions,
EigenMatrix & whitened,
Eigen::VectorXd & prior ) const
nodiscard

The whitened panel L^{-1} K(X, x*) and prior diagonal that the dense Cholesky marginal variance of positions reduces, built by the same assembly and triangular solve as calculateVariance.

Returns
False without a dense training factor.

Definition at line 483 of file Variance.cpp.

486{
487 if (R_matrix.rows() == 0 || R_indices.size() == 0 ||
488 !hasTrainingCholeskyFactor(R_matrix.rows()) || L.rows() == 0)
489 return false;
490 EigenMatrix rows;
491 Eigen::VectorXd indices;
492 aux::AuxiliaryFunctionality{}.assembleMatrixOfRepetitiveCoordinates(
493 positions, rows, indices);
495 rows, indices, /*serial_per_rank=*/false);
496 whitened = trainingSolver().whitenColumns(cross);
497 prior = observationKernelDiagonal(positions);
498 priorFromKernelDiagonal(rows, prior);
499 return true;
500}
EigenMatrix whitenColumns(const EigenMatrix &B) const

◆ devicePosteriorCapableForTesting()

bool gpr::GaussianProcessRegression::devicePosteriorCapableForTesting ( ) const
inlinenodiscard

True when conditioning or an objective evaluation takes the device posterior, so host assembly counters and caches stay untouched.

Definition at line 2737 of file GaussianProcessRegression.h.

2738 {
2739#ifdef GPR_LINALG_KOKKOS
2740 return canUseDevicePosterior();
2741#else
2742 return false;
2743#endif
2744 }

◆ devicePosteriorGradient()

bool gpr::GaussianProcessRegression::devicePosteriorGradient ( Eigen::VectorXd & gradient)
protected

Definition at line 303 of file DevicePosterior.cpp.

304{
305 return false;
306}

◆ devicePosteriorLiveForTesting()

bool gpr::GaussianProcessRegression::devicePosteriorLiveForTesting ( ) const
inlinenodiscardnoexcept

True while the resident device posterior holds the training factor. The host C, L and a are then empty until a reader materializes them.

Definition at line 2716 of file GaussianProcessRegression.h.

2717 {
2718#ifdef GPR_LINALG_KOKKOS
2719 return hasDevicePosterior();
2720#else
2721 return false;
2722#endif
2723 }

◆ disableLaplaceFactorsForTesting()

bool gpr::GaussianProcessRegression::disableLaplaceFactorsForTesting ( )
nodiscard

Build the Laplace posterior if needed and mark every factor unusable, so that a mixture Hessian finds no factor to contract. False when no posterior can be built.

Definition at line 1214 of file LaplacePosterior.cpp.

1215{
1216 if (!ensureLaplacePosterior() || !laplace_posterior_) return false;
1217 for (auto& factor: laplace_posterior_->factors)
1218 factor.valid = false;
1219 return true;
1220}

◆ distributedFactorAppendsForTesting()

std::size_t gpr::GaussianProcessRegression::distributedFactorAppendsForTesting ( ) const
inlinenodiscardnoexcept

Rebuilds that appended to the cached distributed factor.

Definition at line 3290 of file GaussianProcessRegression.h.

3292 {
3293 return distributed_factor_appends_for_testing_;
3294 }

◆ distributedHssvdDualKernelAssemblyCallsForTesting()

std::size_t gpr::GaussianProcessRegression::distributedHssvdDualKernelAssemblyCallsForTesting ( ) const
inlinenodiscardnoexcept

Definition at line 2975 of file GaussianProcessRegression.h.

2976 {
2977 return distributed_hssvd_dual_kernel_assemblies_for_testing_;
2978 }

◆ distributedHssvdDualKernelFactorizationCallsForTesting()

std::size_t gpr::GaussianProcessRegression::distributedHssvdDualKernelFactorizationCallsForTesting ( ) const
inlinenodiscardnoexcept

Definition at line 2985 of file GaussianProcessRegression.h.

2986 {
2987 return distributed_hssvd_dual_kernel_factorizations_for_testing_;
2988 }

◆ distributedTrainingCovarianceAssemblyCallsForTesting()

std::size_t gpr::GaussianProcessRegression::distributedTrainingCovarianceAssemblyCallsForTesting ( ) const
inlinenodiscardnoexcept

Definition at line 3146 of file GaussianProcessRegression.h.

3147 {
3148 return distributed_training_covariance_assemblies_for_testing_;
3149 }

◆ enableRFFFeatureSelection()

void gpr::GaussianProcessRegression::enableRFFFeatureSelection ( double force_tol_fraction = 0.0)
inline

Opt-in choice of the feature count. force_tol_fraction of 0 derives the fraction from the deployed gradient noise; any other value must lie in [0, 1). The default stays off, so a model that never calls this keeps the fixed-count path bit-identical.

Definition at line 2208 of file GaussianProcessRegression.h.

2209 {
2210 if (!std::isfinite(force_tol_fraction) || force_tol_fraction < 0.0 ||
2211 force_tol_fraction >= 1.0) {
2212 throw std::invalid_argument(
2213 "rff force tolerance fraction must be in [0, 1)");
2214 }
2215 rff_force_tol_fraction_ = force_tol_fraction;
2216 rff_features_requested_ = 0;
2217 rff_auto_ = true;
2218 }

◆ enterOptimizationObjectiveFrame()

GaussianProcessRegression::OptimizationObjectiveFrame gpr::GaussianProcessRegression::enterOptimizationObjectiveFrame ( Eigen::VectorXd & targets,
Eigen::Index energy_count,
Eigen::VectorXd * theta )
protected

Definition at line 1548 of file Optimize.cpp.

1550{
1553 lik_gaussian ? lik_gaussian->getSigma2() : 0.0;
1554 frame.saved_jitter_sigma2 = jitter_sigma2;
1555 frame.has_const_covariance = static_cast<bool>(const_cov_fun);
1556 frame.saved_const_sigma2 =
1557 const_cov_fun ? const_cov_fun->getConstSigma2() : 0.0;
1558
1559 if (disable_output_normalization_) {
1560 // Center the energy block first (standardizeTargets divides by
1561 // y_scale_ == 1 under this flag, so it centers only). RMS-scaling
1562 // RAW absolute targets makes the frame scale |mean(E)|-sized: the
1563 // objective then fits a near-constant O(1) energy signal with
1564 // crushed gradients, and the exit un-shift multiplies the fitted
1565 // signal variance by rms^2 ~ E_abs^2 (observed as magnSigma2
1566 // exploding to ~4e4 on raw PET-MAD energies). Centered targets
1567 // give an eV-scale rms and a benign scale-free objective frame.
1568 standardizeTargets(targets, energy_count);
1569 const Eigen::Index m = targets.size();
1570 if (m > 0) {
1571 const double rms =
1572 std::sqrt(targets.squaredNorm() / static_cast<double>(m));
1573 if (std::isfinite(rms) && rms > 0.0) {
1574 frame.target_scale = rms;
1575 targets /= frame.target_scale;
1576 }
1577 }
1578 } else {
1579 standardizeTargets(targets, energy_count);
1580 }
1581
1582 if (frame.target_scale != 1.0) {
1583 const double log_scale = std::log(frame.target_scale);
1584 if (theta != nullptr && theta->size() > 0) {
1585 (*theta)(0) -= 2.0 * log_scale;
1586 }
1587
1588 const double inv_c2 = 1.0 / (frame.target_scale * frame.target_scale);
1589 if (lik_gaussian) {
1590 lik_gaussian->setSigma2(frame.saved_likelihood_sigma2 * inv_c2);
1591 }
1592 jitter_sigma2 = frame.saved_jitter_sigma2 * inv_c2;
1593 if (const_cov_fun) {
1594 const_cov_fun->setConstSigma2(frame.saved_const_sigma2 * inv_c2);
1595 }
1596 if (sexpat_cov_func &&
1597 usesClassicJointEnergyForcePrior(model_profile_)) {
1598 // The prior is a Student-t density on sqrt(signal variance).
1599 // Its location and scale follow the target units; the induced
1600 // log-variance density and its derivatives are invariant.
1601 frame.saved_magnitude_prior =
1602 sexpat_cov_func->getPriorParametersSqrtt();
1603 PriorBase prior = *frame.saved_magnitude_prior;
1604 prior.setMu(prior.getMu() / frame.target_scale);
1605 prior.setS2(prior.getS2() * inv_c2);
1606 sexpat_cov_func->setPriorParametersSqrtt(prior);
1607 }
1608 }
1609
1610 return frame;
1611}
bool usesClassicJointEnergyForcePrior(GPModelProfile profile) noexcept
Definition Structures.h:206

◆ environmentResidualsEnabled()

bool gpr::GaussianProcessRegression::environmentResidualsEnabled ( ) const
inlinenodiscardnoexcept

Definition at line 584 of file GaussianProcessRegression.h.

585 {
586 return environment_residuals_;
587 }

◆ evaluateActiveCovarianceFromGeometry() [1/2]

bool gpr::GaussianProcessRegression::evaluateActiveCovarianceFromGeometry ( const TrainingKernelGeometry & geom,
const Eigen::VectorXd & x_ind,
const Eigen::VectorXd & theta,
const std::vector< bool > & active_lengths,
EigenMatrix & covariance,
bool serial_per_rank,
std::vector< EigenMatrix > * covariance_derivatives,
const std::vector< Eigen::Index > & derivative_lengths )
nodiscard

Select derivative outputs independently of the active covariance's metric. The output contains amplitude followed by requested lengths.

Definition at line 2018 of file CovarianceAssembly.cpp.

2024{
2025 const auto fail = [&]() {
2026 covariance.resize(0, 0);
2027 if (covariance_derivatives != nullptr) covariance_derivatives->clear();
2028 return false;
2029 };
2030 if (!geom.valid || geom.n <= 0 || geom.n != x_ind.size() ||
2031 sexpat_cov_func == nullptr || sexpat_cov_func->usesManifoldChart())
2032 return fail();
2033 Eigen::VectorXd active_theta;
2034 if (!x_ind.allFinite() ||
2035 !activeLogParameters(sexpat_cov_func.get(), theta, active_lengths,
2036 derivative_lengths, active_theta))
2037 return fail();
2038 if (!assembleSexpatCovFromGeometry(
2039 *this, backend(), geom, *sexpat_cov_func, x_ind, covariance,
2040 /*do_reduce=*/true, serial_per_rank, &active_theta,
2041 covariance_derivatives, &derivative_lengths, nullptr, nullptr) ||
2042 !covariance.allFinite())
2043 return fail();
2044 if (covariance_derivatives != nullptr)
2045 for (const auto& derivative: *covariance_derivatives)
2046 if (!derivative.allFinite()) return fail();
2047 return true;
2048}

◆ evaluateActiveCovarianceFromGeometry() [2/2]

bool gpr::GaussianProcessRegression::evaluateActiveCovarianceFromGeometry ( const TrainingKernelGeometry & geom,
const Eigen::VectorXd & x_ind,
const Eigen::VectorXd & theta,
const std::vector< bool > & active_lengths,
EigenMatrix & covariance,
bool serial_per_rank = false,
std::vector< EigenMatrix > * covariance_derivatives = nullptr )
nodiscard

Latent energy-gradient covariance for an independent active correction. The supplied log parameters use the correction's output units. Inactive length scales have zero inverse-square weight; background parameters, noise and cached posterior factors remain owned by the fitted GP. Optional derivatives contain the log amplitude followed by active log lengths in parameter order; inactive derivative matrices are not formed.

Definition at line 2004 of file CovarianceAssembly.cpp.

2009{
2010 std::vector<Eigen::Index> derivative_lengths;
2011 for (std::size_t index = 0; index < active_lengths.size(); ++index)
2012 if (active_lengths[index]) derivative_lengths.push_back(index + 1);
2014 geom, x_ind, theta, active_lengths, covariance, serial_per_rank,
2015 covariance_derivatives, derivative_lengths);
2016}
bool evaluateActiveCovarianceFromGeometry(const TrainingKernelGeometry &geom, const Eigen::VectorXd &x_ind, const Eigen::VectorXd &theta, const std::vector< bool > &active_lengths, EigenMatrix &covariance, bool serial_per_rank=false, std::vector< EigenMatrix > *covariance_derivatives=nullptr)

◆ evaluateCovarianceMatrix()

void gpr::GaussianProcessRegression::evaluateCovarianceMatrix ( const EigenMatrix & x1,
const EigenMatrix & x2,
const Eigen::VectorXd & x1_ind,
const Eigen::VectorXd & x2_ind,
EigenMatrix & C,
bool serial_per_rank = false ) const

Evaluate covariance matrix between two input vectors.

Function takes in Gaussian process GP and two matrixes TX and X that contain input vectors to GP. Returns covariance matrix C. Every element ij of C contains covariance between inputs i in TX and j in X. PREDCF is an optional array specifying the indexes of covariance functions, which are used for forming the matrix. If empty or not given, the matrix is formed with all functions.

Parameters
x1First input vector
x1_indObservation type or derivative-channel indices for rows of x1
x2Second input vector
x2_indObservation type or derivative-channel indices for rows of x2
CCovariance matrix
serial_per_rankAssemble a complete local matrix without a collective reduction

Definition at line 2494 of file CovarianceAssembly.cpp.

2497{
2498 Index_t n = (Index_t)x1.rows();
2499 Index_t n1 = (Index_t)x2.rows();
2500 EigenMatrix Ktemp;
2501 Eigen::VectorXd uDdim, uDdim2;
2502
2503 C.resize(n, n1);
2504
2505 C.setZero();
2506 extractUniqueIndices(x1_ind, uDdim);
2507 extractUniqueIndices(x2_ind, uDdim2);
2508
2509 // applyCrossCovarianceFunction's ownsBlock gating already
2510 // becomes a no-op when do_reduce=false (see the inl-side macro);
2511 // the do_reduce=false branch also skips the trailing MPI_Allreduce.
2512 // serial_per_rank=true therefore translates to do_reduce=false
2513 // here, giving every rank the full kernel without any collective.
2514 const bool do_reduce = !serial_per_rank;
2515 applyCrossCovarianceFunction(x1, x2, x1_ind, uDdim, x2_ind, uDdim2,
2516 *sexpat_cov_func, Ktemp, do_reduce);
2517 C.noalias() += Ktemp;
2518
2519 addConstantCovarianceBlock(const_cov_fun.get(), x1_ind, x2_ind, C);
2520}

◆ evaluateDirectionalCurvature()

bool gpr::GaussianProcessRegression::evaluateDirectionalCurvature ( const Eigen::VectorXd & x_ind,
const EigenMatrix & x,
const Eigen::VectorXd & y,
const Eigen::VectorXd & direction,
double & curvature,
const TrainingKernelGeometry * training_geom = nullptr )

Evaluate the exact directional curvature p^T H p for the current GP objective state.

Returns false when the current kernel parametrization cannot supply a backend-local exact directional derivative path, in which case callers should fall back to the finite-difference probe.

Definition at line 83 of file Hessian.cpp.

87{
88 const auto curvature_start = std::chrono::steady_clock::now();
89 const double solve0 = linalg::teamSolveWallSeconds();
90 const double factor0 = linalg::teamFactorWallSeconds();
91 const double eigen0 = PhaseTimers::eigensolve_seconds;
92 const double kernel0 = PhaseTimers::assembly_seconds;
93 struct ExclusiveCurvature {
94 std::chrono::steady_clock::time_point start;
95 double solve0, factor0, eigen0, kernel0;
96 ~ExclusiveCurvature()
97 {
98 const double wall = std::chrono::duration<double>(
99 std::chrono::steady_clock::now() - start)
100 .count();
101 const double nested = (linalg::teamSolveWallSeconds() - solve0) +
102 (linalg::teamFactorWallSeconds() - factor0) +
103 (PhaseTimers::eigensolve_seconds - eigen0) +
104 (PhaseTimers::assembly_seconds - kernel0);
105 PhaseTimers::curvature_seconds += std::max(0.0, wall - nested);
106 }
107 } exclusive{curvature_start, solve0, factor0, eigen0, kernel0};
108 curvature = std::numeric_limits<double>::quiet_NaN();
109
110 // Rasmussen-Williams 5.9 is the Gaussian NLML Hessian. Student-t, LOO and
111 // LOCAL_LOO energy/gradient already switch; SCG uses the Moller FD probe
112 // when this returns false.
114 hyperparameter_objective_mode_ == HyperparameterObjectiveMode::LOO ||
115 hyperparameter_objective_mode_ ==
117 return false;
118 }
119
120 if (!is_decomposed_succesfully || direction.size() == 0) return false;
121 if (sexpat_cov_func == nullptr) return false;
122 // The analytic oracle is valid for single-pair-type systems:
123 // the closed-form derivation
124 // (Williams-Rasmussen 5.9: -(1/2) tr(ADAD) + (1/2) tr(AE)
125 // + alpha^T DAD alpha - (1/2) alpha^T E alpha) is well-defined for
126 // any n_ls >= 0; assembleDirectionalCovarianceDerivatives + the
127 // SexpatCF kernels handle n_ls=1 correctly.
128
129 // alpha = back_solve(L, b) = K_perm^{-1} (P y) lives in the same permuted
130 // frame as L. The directional derivatives below are assembled in the
131 // original (un-permuted) atom order, so we permute them to match L before
132 // doing the trace algebra. All traces here are basis-invariant under the
133 // symmetric similarity P (·) P^T, so the final scalar curvature is
134 // unaffected by which frame we operate in - what matters is that alpha,
135 // first, second, and L all agree.
136 Eigen::VectorXd uDdim;
137 extractUniqueIndices(x_ind, uDdim);
138
139 // A charted (composite) Sexpat has no pair-distance geometry; its
140 // curvature comes from the composite tensors instead:
141 // d^2 L[p,p] = 1/2 tr(C^-1 C_pp) - 1/2 tr(C^-1 C_p C^-1 C_p)
142 // - 1/2 a^T C_pp a + a^T C_p C^-1 C_p a, a = C^-1 y,
143 // with C_p = sum_i p_i dC/dtheta_i over every covariance direction, plus
144 // noise * p_noise on the diagonal for a learned noise direction, and C_pp
145 // from the second-order tensors
146 // (scripts/derive_chart_second_derivatives.py).
147 if (sexpat_cov_func && sexpat_cov_func->usesManifoldChart()) {
148 std::vector<EigenMatrix> dC;
149 EigenMatrix Cpp;
150 EigenMatrix Cp;
152 x, x_ind, *sexpat_cov_func, dC) ||
154 x, x_ind, *sexpat_cov_func, direction, Cpp) ||
155 !composeChartDirection(
157 lik_gaussian != nullptr && lik_gaussian->getOptimizeSigma2(),
158 direction, Cp, Cpp)) {
159 return false;
160 }
162 evaluateTrainingCovarianceMatrix(x, x_ind, C, /*serial_per_rank=*/true,
163 /*include_constant=*/false);
164 if (jitter_sigma2 > 0.0) C.diagonal().array() += jitter_sigma2;
165 const Eigen::Index n = C.rows();
166 if (n == 0 || y.size() != n || dC[0].rows() != n || Cpp.rows() != n)
167 return false;
168 Eigen::LLT<EigenMatrix> llt(C);
169 if (llt.info() != Eigen::Success) return false;
170 EigenMatrix factor = llt.matrixL();
172 factor,
173 detail::constantCovarianceUpdate(const_cov_fun.get(), x_ind)))
174 return false;
175 const auto solve = [&](const EigenMatrix& rhs) -> EigenMatrix {
176 const EigenMatrix forward =
177 factor.triangularView<Eigen::Lower>().solve(rhs);
178 return factor.transpose().triangularView<Eigen::Upper>().solve(
179 forward);
180 };
181 const Eigen::VectorXd alpha = solve(y);
182 const EigenMatrix CinvCp = solve(Cp);
183 const EigenMatrix CinvCpp = solve(Cpp);
184 const Eigen::VectorXd Cp_alpha = Cp * alpha;
185 const Eigen::VectorXd solved_Cp_alpha = solve(Cp_alpha);
186 curvature =
187 0.5 * CinvCpp.trace() -
188 0.5 * (CinvCp.cwiseProduct(CinvCp.transpose())).sum() -
189 0.5 * alpha.dot(Cpp * alpha) + Cp_alpha.dot(solved_Cp_alpha) -
190 sexpat_cov_func->calculateDirectionalLogPriorCurvature(direction);
191 return std::isfinite(curvature);
192 }
193 EigenMatrix first, second;
194 bool derivatives_ready = false;
195 // Prefer the precomputed-geometry derivative assembly even when the caller
196 // did not pass a geometry: build one locally. The geometry and live-rebuild
197 // paths round the shared kernel differently, and the Q-form curvature
198 // amplifies that by 1/sigma^2; routing both through the geometry assembly
199 // makes the curvature path-invariant (geometry-passed vs not) to rounding.
200 // Pair tiles reuse the fit's geometry cache. That cache is coordinates,
201 // channels and the kernel geometry; theta, the probe direction and the
202 // Cholesky factor are not stored in it.
203 TrainingKernelGeometry local_geom;
204 if (training_geom == nullptr) {
205 if (use_pair_local_directional_tiles_ && use_pair_local_tiles_)
206 training_geom = fitGeometryFor(x, x_ind);
207 else if (prepareTrainingKernelGeometry(x, x_ind, local_geom))
208 training_geom = &local_geom;
209 }
210 if (training_geom != nullptr) {
211 derivatives_ready =
213 *training_geom, x, x_ind, uDdim, direction, first, second,
214 /*serial_per_rank=*/false);
215 }
216 if (!derivatives_ready) {
217 assembleDirectionalCovarianceDerivatives(x, x_ind, uDdim, direction,
218 first, second,
219 /*serial_per_rank=*/false);
220 }
221
222 if (first.size() == 0 || second.size() == 0) return false;
223
224 // Energy/gradient on the HS-SVD contractions path cache a Cholesky
225 // factor of the same C (hssvd_objective_trace_via_cholesky_). The
226 // Q-form Woodbury contraction of that cache is a different K^{-1}
227 // and diverges by O(cond * eps) from the Cholesky reduction SCG
228 // just used for E/g. assembleExactHessian and the gradient walk
229 // already refuse that mix; the directional oracle must too.
230 const bool use_hssvd_curvature =
231 use_hssvd_backend_ && use_hssvd_objective_contractions_ &&
232 hssvdObjectiveStampMatches() && !hssvd_objective_trace_via_cholesky_ &&
233 hssvd_objective_alpha_.size() == y.size() &&
234 hssvd_objective_trace_basis_.rows() == y.size() &&
235 hssvd_objective_trace_weighted_basis_.rows() == y.size() &&
236 hssvd_objective_trace_basis_.cols() ==
237 hssvd_objective_trace_weighted_basis_.cols();
238
239 if (use_hssvd_curvature) {
240 const EigenMatrix& Q = hssvd_objective_trace_basis_;
241 const EigenMatrix& Qshrink = hssvd_objective_trace_weighted_basis_;
242 const Eigen::VectorXd& alpha = hssvd_objective_alpha_;
243 const double inv_noise = hssvd_objective_trace_inv_noise_;
244
245 const double prior_curvature =
246 -sexpat_cov_func->calculateDirectionalLogPriorCurvature(direction);
247 EigenMatrix solve_first;
248 Eigen::VectorXd z;
249 double trace_ae = 0.0;
250 if (hssvd_objective_trace_direct_inverse_) {
251 solve_first = Qshrink * (Q.transpose() * first);
252 const Eigen::VectorXd v_direct = first * alpha;
253 z = Qshrink * (Q.transpose() * v_direct);
254 trace_ae = (Q.array() * (second * Qshrink).array()).sum();
255 } else if (inv_noise > 0.0) {
256 solve_first =
257 inv_noise * (first - Qshrink * (Q.transpose() * first));
258 const double projected_trace =
259 (Q.array() * (second * Qshrink).array()).sum();
260 trace_ae = inv_noise * (second.trace() - projected_trace);
261 } else {
262 return false;
263 }
264 const double trace_adad =
265 backend().trace_product(solve_first, solve_first.transpose());
266 const Eigen::VectorXd v = first * alpha;
267 if (!hssvd_objective_trace_direct_inverse_) {
268 z = inv_noise * (v - Qshrink * (Q.transpose() * v));
269 }
270 const double quad = v.dot(z);
271 const double alpha_e_alpha = alpha.dot(second * alpha);
272
273 curvature =
274 0.5 * (-trace_adad + trace_ae + 2.0 * quad - alpha_e_alpha) +
275 prior_curvature;
276 return std::isfinite(curvature);
277 }
278
282 }
283
284 // One trace formula at every rank count. A distributed build takes the
285 // trace of C^{-1} second from the inverse of the cached factor, formed
286 // by the same tile-ordered routine and summed exactly at one rank as at
287 // several, so the rounding does not change with the rank count; the
288 // inverse is not cached. A serial build has one path.
289#ifdef GPR_LINALG_SCALAPACK
290 const bool use_solve_based_trace = true;
291#else
292 const bool use_solve_based_trace = false;
293#endif
294
295 const double prior_curvature =
296 -sexpat_cov_func->calculateDirectionalLogPriorCurvature(direction);
297
298 const bool factor_ready = hasTrainingCholeskyFactor(y.rows());
299 if (b.rows() != activeFactorOrder(y.rows()) || !factor_ready) {
300 // Distributed Cholesky leaves the dense member empty. Ownership
301 // and order distinguish its live factor from a consumed or foreign
302 // factor before the triangular solves.
303 if (!factor_ready && x.rows() > 0) {
304 (void)decomposeCovarianceMatrix(x, x_ind);
305 if (!is_decomposed_succesfully) return false;
306 }
308 }
309
310 // A device-resident posterior leaves b empty and keeps the weights on the
311 // device.
312 Eigen::VectorXd alpha;
313#ifdef GPR_LINALG_KOKKOS
314 if (hasDevicePosterior()) {
316 alpha = a;
317 } else
318#endif
319 alpha = trainingSolver().unwhiten(b);
320 // The deflated objective is block diagonal in [T, U]: the factor carries
321 // T^T C T and the rigid block is the noise alone. Contract the projected
322 // derivatives against the factor and add the rigid block in closed form.
323 const bool deflated = rigid_deflation_.isActiveForFullOrder(y.rows());
324 double rigid_curvature = 0.0;
325 if (deflated) {
326 if (alpha.size() != rigid_deflation_.deflated_rows) return false;
327 if (rigid_deflation_.a_rigid.size() != y.rows()) {
328 rigid_deflation_.updateTargetStats(
330 }
331 first = rigid_deflation_.projectSymmetric(first);
332 second = rigid_deflation_.projectSymmetric(second);
333 const auto [noise_first, noise_second] =
334 rigidNoiseDerivatives(direction);
335 rigid_curvature = rigid_deflation_.rigidCurvature(
336 noise_first, noise_first, noise_second);
337 }
338 const EigenMatrix solve_first = trainingSolver().solveColumns(first);
339 const double trace_adad =
340 backend().trace_product(solve_first, solve_first.transpose());
341 const Eigen::VectorXd v = first * alpha;
342 const Eigen::VectorXd z = trainingSolver().solve(v);
343
344 double trace_ae = 0.0;
345 if (use_solve_based_trace) {
346#ifdef GPR_LINALG_SCALAPACK
347 trace_ae = backend().trace_inverse_times_symmetric(L, second);
348#endif
349 } else {
350 trace_ae = backend().trace_product(trainingSolver().inverse(), second);
351 }
352
353 const double quad = v.dot(z);
354 const double alpha_e_alpha = alpha.dot(second * alpha);
355
356 curvature = 0.5 * (-trace_adad + trace_ae + 2.0 * quad - alpha_e_alpha) +
357 rigid_curvature + prior_curvature;
358 return std::isfinite(curvature);
359}
bool assembleCompositeJointCovarianceDerivatives(const EigenMatrix &x, const Eigen::VectorXd &indices, SexpatCF &covariance, std::vector< EigenMatrix > &derivatives) const
bool assembleCompositeJointCovarianceSecondDerivative(const EigenMatrix &x, const Eigen::VectorXd &indices, SexpatCF &covariance, const Eigen::VectorXd &direction, EigenMatrix &second) const
double teamFactorWallSeconds()
double teamSolveWallSeconds()
static double eigensolve_seconds
static double assembly_seconds

◆ evaluateEnergy() [1/2]

double gpr::GaussianProcessRegression::evaluateEnergy ( const Eigen::VectorXd & w,
const EigenMatrix & x,
const Eigen::VectorXd & x_ind,
const Eigen::VectorXd & y )

Definition at line 366 of file EnergyGradient.cpp.

370{
371 if (!detail::logParametersAreRepresentable(w)) {
372 return std::numeric_limits<double>::infinity();
373 }
374 if (hyperparameter_objective_mode_ ==
376 return evaluateLocalNeighborhoodLooEnergy(w, x, x_ind, y);
377 }
378 if (use_hssvd_backend_ && use_hssvd_objective_contractions_ &&
380 hyperparameter_objective_mode_ != HyperparameterObjectiveMode::LOO) {
381 if (const TrainingKernelGeometry* geom = fitGeometryFor(x, x_ind)) {
382 const double energy =
383 evaluateEnergyFromGeometry(w, *geom, x, x_ind, y);
384 if (std::isfinite(energy)) last_objective_theta_ = w;
385 return energy;
386 }
387 }
388
389 setParameters(w);
390 const double energy = evaluateEnergy(x, x_ind, y);
391 if (std::isfinite(energy)) last_objective_theta_ = w;
392 return energy;
393}
double evaluateEnergyFromGeometry(const Eigen::VectorXd &w, const TrainingKernelGeometry &geom, const EigenMatrix &x, const Eigen::VectorXd &x_ind, const Eigen::VectorXd &y)
double evaluateLocalNeighborhoodLooEnergy(const Eigen::VectorXd &w, const EigenMatrix &x, const Eigen::VectorXd &x_ind, const Eigen::VectorXd &y)

◆ evaluateEnergy() [2/2]

double gpr::GaussianProcessRegression::evaluateEnergy ( const EigenMatrix & x,
const Eigen::VectorXd & x_ind,
const Eigen::VectorXd & y )
protectedvirtual

Evaluate the energy function (un-normalized negative log marginal posterior).

This function takes a Gaussian process structure GP together with a matrix X of input vectors and a matrix Y of targets, and evaluates the energy function E. Each row of X corresponds to one input vector and each row of Y corresponds to one target vector.

The energy is minus log posterior cost function: E = EDATA + EPRIOR = - log p(Y|X, th) - log p(th), where th represents the parameters (lengthScale, magnSigma2...), X is inputs and Y is observations (regression) or latent values (non-Gaussian likelihood).

Note that this implements Algo 2.1 of Rasmussen and Williams but the variance is not computed, and the mean is not returned, so only the log marginal liklihood is caclulated and used directly to predict.

OPTIONS is optional parameter-value pair z - optional observed quantity in triplet (x_i,y_i,z_i) Some likelihoods may use this. For example, in case of Poisson likelihood we have z_i=E_i, that is, expected value for ith case.

Parameters
xMatrix of coordinates
x_indPer-row observation channel indices, aligned with x
yVector of energy and gradients
Returns
Energy Calculated new energy

Reimplemented in gpr::StudentTProcessRegression.

Definition at line 423 of file EnergyGradient.cpp.

426{
427#ifdef GPR_LINALG_KOKKOS
428 if (const auto value = conditionDevicePosterior(x, x_ind, y))
429 return unregularized_marginal_likelihood_
430 ? *value
431 : *value - const_cov_fun->calculateLogPrior() -
432 sexpat_cov_func->calculateLogPrior() -
433 lik_gaussian->evaluateLogPrior();
434#endif
435 // Precomputed-geometry objective fast path, kept behind this virtual so a
436 // subclass that overrides evaluateEnergy intercepts it.
437 // active_training_geom_ and active_training_w_ are set by the geometry
438 // objective entry points around their virtual call (and cleared right
439 // after).
440 if (active_training_geom_ != nullptr && active_training_w_ != nullptr) {
441 const TrainingKernelGeometry* geom = active_training_geom_;
442 const Eigen::VectorXd* w = active_training_w_;
443 active_training_geom_ = nullptr;
444 active_training_w_ = nullptr;
445 return evaluateEnergyFromGeometry(*w, *geom, x, x_ind, y);
446 }
447 const bool profile_energy_split = profile_energy_split_;
448 auto reduce_max_seconds = [&](const double local_seconds) {
449#ifdef GPR_LINALG_SCALAPACK
450 int mpi_up = 0;
451 MPI_Initialized(&mpi_up);
452 if (!mpi_up) return local_seconds;
453
454 int nprocs = 1;
455 MPI_Comm_size(mpiContext().comm, &nprocs);
456 if (nprocs == 1) return local_seconds;
457
458 const double send_seconds = local_seconds;
459 double global_seconds = 0.0;
460 MPI_Allreduce(&send_seconds, &global_seconds, 1, MPI_DOUBLE, MPI_MAX,
461 mpiContext().comm);
462 return global_seconds;
463#else
464 return local_seconds;
465#endif
466 };
467 auto elapsed_seconds =
468 [&](const std::chrono::steady_clock::time_point& start) {
469 return std::chrono::duration<double>(
470 std::chrono::steady_clock::now() - start)
471 .count();
472 };
473
474 Index_t n = (Index_t)x.rows();
475 double zc = 0., edata = 0., eprior = 0.;
476 double energy = 0.;
477
478 const auto decompose_start = std::chrono::steady_clock::now();
480 const double decompose_seconds =
481 profile_energy_split
482 ? reduce_max_seconds(elapsed_seconds(decompose_start))
483 : 0.0;
484
485 // Test if the matrix is positive definite
487 if (report_level >= 1)
488 log_man << "Warning! Matrix L is not positive definite\n";
489 energy = std::numeric_limits<double>::quiet_NaN();
490 ;
491 } else {
492 const auto posterior_start = std::chrono::steady_clock::now();
494
496 const Index_t n_eff = rigid_deflation_.isActiveForFullOrder(n)
497 ? rigid_deflation_.deflated_rows
498 : n;
499 edata = 0.5 * n_eff * numerics::log(2 * M_PI) + zc +
500 0.5 * b.dot(b); // Line 7, zc should be negative
501 if (rigid_deflation_.isActiveForFullOrder(n)) {
502 edata += rigid_deflation_.nlmlPenalty();
503 }
504
505 // Evaluate the prior contribution to the error from covariance
506 // functions
507#ifndef NDEBUG
508 gpr::assertMsg(const_cov_fun != nullptr,
509 "Object of Gausian likelihood is not allocated!");
510 gpr::assertMsg(sexpat_cov_func != nullptr,
511 "Object of Gausian likelihood is not allocated!");
512#endif
513
514 eprior -= const_cov_fun->calculateLogPrior();
515
516 eprior -= sexpat_cov_func->calculateLogPrior();
517
518 // Evaluate the prior contribution to the error from Gaussian likelihood
519 eprior -= lik_gaussian->evaluateLogPrior();
520
521 energy = edata + eprior;
522 const double posterior_seconds =
523 profile_energy_split
524 ? reduce_max_seconds(elapsed_seconds(posterior_start))
525 : 0.0;
526 if (profile_energy_split) {
527 recordEnergyProfileSplit(0.0, decompose_seconds, posterior_seconds);
528 }
529 }
530
531 if (profile_energy_split && !is_decomposed_succesfully) {
532 recordEnergyProfileSplit(0.0, decompose_seconds, 0.0);
533 }
534 // std::cout << "\n in evaluateEnergy(): \n" << y << "\n\n";
535 return energy;
536}

◆ evaluateEnergyAndGradient()

void gpr::GaussianProcessRegression::evaluateEnergyAndGradient ( const Eigen::VectorXd & w,
const EigenMatrix & x,
const Eigen::VectorXd & x_ind,
const Eigen::VectorXd & y,
EnergyAndGradient & energy_and_gradient )

Evaluate the energy function (un-normalized negative marginal log posterior) and its gradient.

This function takes a Gaussian process structure GP together with a matrix X of input vectors and a matrix Y of targets, and evaluates the energy function E and its gradient G. Each row of X corresponds to one input vector and each row of Y corresponds to one target vector.

The energy is minus log posterior cost function: E = EDATA + EPRIOR = - log p(Y|X, th) - log p(th), where th represents the parameters (lengthScale, magnSigma2...), X is inputs and Y is observations (regression) or latent values (non-Gaussian likelihood).

Parameters
wVector of combined parameters from covariance functions and likelihood
xTraining input vectors
x_indPer-row observation type or derivative-channel indices
yObserved target values aligned with the rows of x
energy_and_gradientOutput energy and parameter gradient

Definition at line 136 of file EnergyGradient.cpp.

140{
141 if (detail::rejectInvalidHyperparameters(w, energy_and_gradient)) return;
142 if (hyperparameter_objective_mode_ ==
144 // Neighborhood LOO needs neither the full-training geometry cache
145 // nor the HS-SVD backend (each held-out geometry gets its own
146 // small dense solve), so it bypasses the geometry auto-build
147 // below entirely. The geometry argument is unused (see the
148 // declaration in GaussianProcessRegression.h).
149 const TrainingKernelGeometry unused_geometry;
151 w, unused_geometry, x, x_ind, y, energy_and_gradient);
152 return;
153 }
155 ScopedPhaseTimer objective_timer(PhaseTimers::objective_seconds);
158 if (use_hssvd_backend_ && use_hssvd_objective_contractions_ &&
160 hyperparameter_objective_mode_ != HyperparameterObjectiveMode::LOO) {
161 // The block geometry does not depend on theta: one build serves
162 // every evaluation of the fit (16_oxirane: 31 evaluations per
163 // refit each rebuilt and streamed the 3403 blocks of the same ten
164 // configurations, 0.5 s each).
165 if (const TrainingKernelGeometry* geom = fitGeometryFor(x, x_ind)) {
166 evaluateEnergyAndGradientFromGeometry(w, *geom, x, x_ind, y,
168 return;
169 }
170 }
171
172 setParameters(w);
173
174 energy_and_gradient.energy = evaluateEnergy(x, x_ind, y);
175
176 if (!std::isfinite(energy_and_gradient.energy) ||
177 fabs(energy_and_gradient.energy) <= DBL_EPSILON) {
178 if (report_level >= 1) {
179 if (!std::isfinite(energy_and_gradient.energy)) {
180 log_man << "Energy is not finite; skipping gradient "
181 "evaluation.\n";
182 } else {
183 log_man << "Energy field is empty!\n";
184 }
185 }
186 // When energy is non-finite, fall back to a sized zero gradient.
187 // setConstant(NaN) cascades through SCG's evaluate_penalized retry
188 // loop and corrupts the next iteration's gamma = (p.dot(r_new - r))
189 // / sigma step.
190 energy_and_gradient.gradient.resize(w.size());
191 energy_and_gradient.gradient.setZero();
192 } else {
193 evaluateGradient(x, x_ind, y, energy_and_gradient.gradient);
194 }
195}
void evaluateLocalNeighborhoodLooEnergyAndGradientFromGeometry(const Eigen::VectorXd &w, const TrainingKernelGeometry &geom, const EigenMatrix &x, const Eigen::VectorXd &x_ind, const Eigen::VectorXd &y, EnergyAndGradient &energy_and_gradient)
virtual void evaluateGradient(const EigenMatrix &x, const Eigen::VectorXd &x_ind, const Eigen::VectorXd &y, Eigen::VectorXd &gradient)
Evaluate the gradient of energy (GP_E) for Gaussian Process.
static long objective_channels
static double objective_seconds
static long objective_rows
static int objective_count

◆ evaluateEnergyAndGradientFromGeometry()

void gpr::GaussianProcessRegression::evaluateEnergyAndGradientFromGeometry ( const Eigen::VectorXd & w,
const TrainingKernelGeometry & geom,
const EigenMatrix & x,
const Eigen::VectorXd & x_ind,
const Eigen::VectorXd & y,
EnergyAndGradient & energy_and_gradient )

Definition at line 1150 of file EnergyGradient.cpp.

1154{
1155 if (detail::rejectInvalidHyperparameters(w, energy_and_gradient)) return;
1157 ScopedPhaseTimer objective_timer(PhaseTimers::objective_seconds);
1160 // Route the scalar energy through the virtual evaluateEnergy so a subclass
1161 // that overrides it (e.g. forcing a non-finite energy to exercise the
1162 // optimizer rollback) intercepts the geometry fast path. setParameters is
1163 // applied inside the geometry path; pre-set it here so the virtual sees the
1164 // active hyperparameters.
1165 setParameters(w);
1166 active_training_geom_ = &geom;
1167 active_training_w_ = &w;
1168 energy_and_gradient.energy = evaluateEnergy(x, x_ind, y);
1169 active_training_geom_ = nullptr;
1170 active_training_w_ = nullptr;
1171#ifdef GPR_LINALG_SCALAPACK
1172 // Every rank must make the same decision before the gradient's solves.
1173 // A rank-local non-finite energy invalidates the collective objective.
1174 const auto process_group = mpiContext();
1175 if (process_group.is_distributed()) {
1176 int finite_energy = std::isfinite(energy_and_gradient.energy) ? 1 : 0;
1177 MPI_Allreduce(MPI_IN_PLACE, &finite_energy, 1, MPI_INT, MPI_MIN,
1178 process_group.comm);
1179 if (finite_energy == 0)
1180 energy_and_gradient.energy =
1181 std::numeric_limits<double>::quiet_NaN();
1182 }
1183#endif
1184 if (!std::isfinite(energy_and_gradient.energy)) {
1185 energy_and_gradient.gradient.resize(w.size());
1186 energy_and_gradient.gradient.setZero();
1187 return;
1188 }
1189
1190 // The geometry handle covers K(theta) assembly and the SExp dK/dtheta
1191 // block walk. Other covariance functions keep the live assembly path.
1193 &geom);
1194}
void evaluateGradientWithGeometry(const EigenMatrix &x, const Eigen::VectorXd &x_ind, const Eigen::VectorXd &y, Eigen::VectorXd &gradient, const TrainingKernelGeometry *training_geom)

◆ evaluateEnergyAndGradientLocal()

void gpr::GaussianProcessRegression::evaluateEnergyAndGradientLocal ( const Eigen::VectorXd & w,
const EigenMatrix & x,
const Eigen::VectorXd & x_ind,
const Eigen::VectorXd & y,
EnergyAndGradient & energy_and_gradient )

Local-only counterpart to evaluateEnergyAndGradient: every linear algebra step uses Eigen LLT on the rank's local heap rather than the ScaLAPACK collective Cholesky. Required by callers that want to evaluate the GP NLML at many hyperparameter samples in parallel across MPI ranks (each rank holds a different theta); a collective inside that loop would either deadlock or feed different matrices into the same global call.

Mutates rank-local kernel state via setParameters(w) the same way the distributed evaluator does; pair with ScopedKernelState at the call-site if the caller needs to restore (magn, ls, sigma2) after a sweep.

Does NOT touch member L, b, a, or C (the distributed Cholesky state); writes only into the caller-supplied energy_and_gradient out parameter.

Definition at line 197 of file EnergyGradient.cpp.

201{
202 if (detail::rejectInvalidHyperparameters(w, energy_and_gradient)) return;
203 // Local-only NLML + gradient evaluator. Uses Eigen LLT on a stack-
204 // local copy of the training kernel; never enters the ScaLAPACK
205 // collective Cholesky path and never mutates rigid_deflation_. Required
206 // by the SVGD particle oracle distributed across MPI ranks: each rank
207 // holds a different theta_k and a collective Cholesky would either
208 // deadlock or feed different matrices into the same global call.
209 const detail::RigidDeflationState no_deflation;
210 setParameters(w);
211
212 const Eigen::Index n = x.rows();
213
214 // Build the training kernel matrix on this rank only:
215 // serial_per_rank=true skips the round-robin block distribution
216 // and the MPI_Reduce that the default assembly fires. Required by
217 // the SVGD per-rank oracle (each rank holds a different theta_k;
218 // a collective would deadlock on mismatched matrices).
219 EigenMatrix C_local;
220 TrainingKernelGeometry geometry;
221 const TrainingKernelGeometry* gradient_geometry = nullptr;
222 if (use_training_geometry_handle_ &&
223 // Objective values share the reusable fit's derivative arithmetic;
224 // retaining geometry changes its storage, not its kernel values.
225 prepareTrainingKernelGeometry(x, x_ind, geometry, /*reused=*/true) &&
227 geometry, x, x_ind, C_local, /*serial_per_rank=*/true,
228 /*include_constant=*/false)) {
229 // Alpha and inverse entries use the original observation channels;
230 // the full geometry has the same ordering on every particle rank.
231 // Its derivative tensors serve both assembly and this gradient.
232 gradient_geometry = &geometry;
233 } else {
234 evaluateTrainingCovarianceMatrix(x, x_ind, C_local,
235 /*serial_per_rank=*/true,
236 /*include_constant=*/false);
237 }
239 Eigen::VectorXd constant_update =
240 detail::constantCovarianceUpdate(const_cov_fun.get(), x_ind);
241 EigenMatrix C_factor = C_local;
242 Eigen::VectorXd y_factor = y;
245 y_factor = permuteTrainingVector(y_factor);
246 constant_update = permuteTrainingVector(constant_update);
247 }
248 if (jitter_sigma2 > 0.0) C_factor.diagonal().array() += jitter_sigma2;
249 Eigen::VectorXd uDdim_local;
250 extractUniqueIndices(x_ind, uDdim_local);
251
252 Eigen::VectorXd alpha_local;
253 Eigen::VectorXd alpha_factor;
254 Eigen::VectorXd b_local;
255 double log_det = 0.0;
256 bool factorise_ok = true;
257
258 Eigen::LLT<EigenMatrix> llt(C_factor);
259 EigenMatrix matrix_llt;
260 if (llt.info() == Eigen::Success) matrix_llt = llt.matrixL();
261 factorise_ok = llt.info() == Eigen::Success &&
262 linalg::rank_one_update_lower(matrix_llt, constant_update);
263 if (factorise_ok) {
264 const auto lower = matrix_llt.template triangularView<Eigen::Lower>();
265 b_local = lower.solve(y_factor);
266 alpha_factor = lower.adjoint().solve(b_local);
267 log_det = matrix_llt.diagonal().array().log().sum();
269 alpha_local =
271 } else {
272 alpha_local = alpha_factor;
273 }
274 // cond(K) ~ (max L_ii / min L_ii)^2 from the Cholesky diagonal; track
275 // it and max|alpha| to attribute the FP hypersensitivity.
276 {
277 const auto ldiag = matrix_llt.diagonal().array().abs();
278 const double lmin = ldiag.minCoeff();
279 const double lmax = ldiag.maxCoeff();
280 if (lmin > 0.0) {
281 const double ratio = lmax / lmin;
282 const double cond = ratio * ratio;
283 if (cond > g_max_cond_k) g_max_cond_k = cond;
284 }
285 if (alpha_local.size() > 0) {
286 const double amax = alpha_local.cwiseAbs().maxCoeff();
287 if (amax > g_max_abs_alpha) g_max_abs_alpha = amax;
288 }
289 }
290 }
291
292 if (!factorise_ok) {
293 // Non-PD kernel -- fall back to NaN energy + zero gradient,
294 // mirroring the distributed evaluator's failure path so SVGD
295 // (and other consumers) treat both backends identically.
296 energy_and_gradient.energy = std::numeric_limits<double>::quiet_NaN();
297 energy_and_gradient.gradient.resize(w.size());
298 energy_and_gradient.gradient.setZero();
299 return;
300 }
301
302 // log marginal likelihood: 0.5 n log(2 pi) + sum(log diag(L))
303 // + 0.5 ||L^{-1} y||^2 - log p(theta).
304 const double e_data =
305 0.5 * static_cast<double>(n) * numerics::log(2.0 * M_PI) + log_det +
306 0.5 * b_local.squaredNorm();
307 double e_prior = 0.0;
308 if (const_cov_fun) e_prior -= const_cov_fun->calculateLogPrior();
309 if (sexpat_cov_func) e_prior -= sexpat_cov_func->calculateLogPrior();
310 if (lik_gaussian) e_prior -= lik_gaussian->evaluateLogPrior();
311
312 const double energy = e_data + e_prior;
313 energy_and_gradient.energy = energy;
314
315 if (!std::isfinite(energy) ||
316 std::fabs(energy) <= std::numeric_limits<double>::epsilon()) {
317 // Mirror evaluateEnergyAndGradient: SCG's evaluate_penalized
318 // retry loop expects a sized zero gradient (not NaN) on
319 // degenerate energies.
320 energy_and_gradient.gradient.resize(w.size());
321 energy_and_gradient.gradient.setZero();
322 return;
323 }
324
325 // Gradient w.r.t. hyperparameters. The quadratic term is alpha alpha^T.
326 // The trace solves against each dK instead of forming K^{-1}.
327 FieldMatrixd gdata;
328 FieldMatrixd gprior;
329 const EigenMatrix no_inverse;
330 calculateGradientWithCovFunc(x, x_ind, uDdim_local, alpha_local, no_inverse,
331 *const_cov_fun, gdata, gprior,
332 /*serial_per_rank=*/true, gradient_geometry,
333 &matrix_llt, &no_deflation);
334 calculateGradientWithCovFunc(x, x_ind, uDdim_local, alpha_local, no_inverse,
335 *sexpat_cov_func, gdata, gprior,
336 /*serial_per_rank=*/true, gradient_geometry,
337 &matrix_llt, &no_deflation);
338
339 FieldMatrixd gprior_lik;
340 if (lik_gaussian) lik_gaussian->evaluateLogPriorGradient(gprior_lik);
341 if (gprior_lik.size() != 0) {
342 gprior_lik *= -1.;
343 gpr::field::appendRows(gprior, gprior_lik);
344 }
345
346 // matrix_llt is this rank's Eigen LLT. The noise trace has to stay
347 // on that dense factor. A collective trace_inverse would write it
348 // over the shared distributed factor cache.
349 appendLikelihoodNoiseGradient(alpha_local, no_inverse, matrix_llt,
350 /*use_solve_based_trace=*/true, gdata, gprior,
351 &no_deflation);
352
353 if (gprior.size() != 0) {
354 if (energy_and_gradient.gradient.rows() != gprior.size()) {
355 energy_and_gradient.gradient.resize(gprior.size());
356 }
357 energy_and_gradient.gradient =
358 Eigen::Map<const Eigen::VectorXd>(gdata.data(), gdata.size()) +
359 Eigen::Map<const Eigen::VectorXd>(gprior.data(), gprior.size());
360 } else {
361 energy_and_gradient.gradient.resize(w.size());
362 energy_and_gradient.gradient.setZero();
363 }
364}
void prepareTrainingPermutationLocal(const Eigen::VectorXd &x_ind)
void appendRows(Eigen::PlainObjectBase< Derived > &mat, const Eigen::PlainObjectBase< Derived > &other)
double g_max_cond_k

◆ evaluateEnergyFromGeometry()

double gpr::GaussianProcessRegression::evaluateEnergyFromGeometry ( const Eigen::VectorXd & w,
const TrainingKernelGeometry & geom,
const EigenMatrix & x,
const Eigen::VectorXd & x_ind,
const Eigen::VectorXd & y )

Definition at line 592 of file EnergyGradient.cpp.

596{
597 if (!detail::logParametersAreRepresentable(w)) {
598 return std::numeric_limits<double>::infinity();
599 }
600 const auto energy_start = std::chrono::steady_clock::now();
601 const double solve0 = linalg::teamSolveWallSeconds();
602 const double factor0 = linalg::teamFactorWallSeconds();
603 const double eigen0 = PhaseTimers::eigensolve_seconds;
604 const double kernel0 = PhaseTimers::assembly_seconds;
605 const double curvature0 = PhaseTimers::curvature_seconds;
606 struct ExclusiveEnergy {
607 std::chrono::steady_clock::time_point start;
608 double solve0, factor0, eigen0, kernel0, curvature0;
609 ~ExclusiveEnergy()
610 {
611 const double wall = std::chrono::duration<double>(
612 std::chrono::steady_clock::now() - start)
613 .count();
614 const double nested = (linalg::teamSolveWallSeconds() - solve0) +
615 (linalg::teamFactorWallSeconds() - factor0) +
616 (PhaseTimers::eigensolve_seconds - eigen0) +
617 (PhaseTimers::assembly_seconds - kernel0) +
618 (PhaseTimers::curvature_seconds - curvature0);
619 PhaseTimers::energy_seconds += std::max(0.0, wall - nested);
620 }
621 } exclusive_energy{energy_start, solve0, factor0,
622 eigen0, kernel0, curvature0};
623 // Objective evaluations replace the cached factor independently of the
624 // fitted posterior. Its append signature cannot describe that factor.
625#ifdef GPR_LINALG_SCALAPACK
626 distributed_factor_signature_.valid = false;
627#endif
628 serial_factor_signature_.valid = false;
629 setParameters(w);
630#ifdef GPR_LINALG_KOKKOS
632 const double energy = evaluateEnergy(x, x_ind, y);
633 if (std::isfinite(energy)) last_objective_theta_ = w;
634 return energy;
635 }
636#endif
637 hssvd_objective_basis_valid_ = false;
638 clearHssvdPendingCovariance();
639 hssvd_objective_alpha_.resize(0);
640 hssvd_objective_trace_basis_.resize(0, 0);
641 hssvd_objective_trace_weighted_basis_.resize(0, 0);
642 hssvd_objective_trace_inv_noise_ = 0.0;
643 hssvd_objective_trace_direct_inverse_ = false;
644 hssvd_objective_trace_via_cholesky_ = false;
645 hssvd_trace_basis_ = nullptr;
646 hssvd_trace_weighted_basis_ = nullptr;
647 hssvd_trace_inv_noise_ = 0.0;
648 hssvd_trace_direct_inverse_ = false;
649 const bool profile_energy_split = profile_energy_split_;
650 auto reduce_max_seconds = [&](const double local_seconds) {
651#ifdef GPR_LINALG_SCALAPACK
652 int mpi_up = 0;
653 MPI_Initialized(&mpi_up);
654 if (!mpi_up) return local_seconds;
655
656 int nprocs = 1;
657 MPI_Comm_size(mpiContext().comm, &nprocs);
658 if (nprocs == 1) return local_seconds;
659
660 const double send_seconds = local_seconds;
661 double global_seconds = 0.0;
662 MPI_Allreduce(&send_seconds, &global_seconds, 1, MPI_DOUBLE, MPI_MAX,
663 mpiContext().comm);
664 return global_seconds;
665#else
666 return local_seconds;
667#endif
668 };
669 auto elapsed_seconds =
670 [&](const std::chrono::steady_clock::time_point& start) {
671 return std::chrono::duration<double>(
672 std::chrono::steady_clock::now() - start)
673 .count();
674 };
675
676 // Geometry-driven training-cov assembly. Same algebraic K(theta) as
677 // evaluateTrainingCovarianceMatrix, but the per-block geometric work
678 // (dist_at + per-pair derivatives) was paid once in
679 // prepareTrainingKernelGeometry and is just elementwise-applied here.
680 const auto covariance_start = std::chrono::steady_clock::now();
682 rigid_deflation_.reset();
683 rigid_deflation_diag_ = RigidDeflationDiagnostic{};
684 Eigen::VectorXd constant_update = permuteTrainingVector(
685 detail::constantCovarianceUpdate(const_cov_fun.get(), x_ind));
686 bool distributed_covariance = false;
687 bool covariance_valid = true;
689 detail::validateRigidNullDeflationConfiguration(true,
690 principled_nugget_);
691 }
692#ifdef GPR_LINALG_SCALAPACK
693 std::vector<double> covariance_owned;
694 int covariance_descriptor[9];
695 if ((!use_hssvd_backend_ || use_hssvd_objective_contractions_) &&
696 !use_correction_) {
697 const auto status = assembleTrainingCovarianceDistributedFromGeometry(
698 geom, x, x_ind, covariance_owned, covariance_descriptor);
699 covariance_valid = status != DistributedCovarianceStatus::Invalid;
700 distributed_covariance =
701 status == DistributedCovarianceStatus::Assembled;
702 }
703#endif
704 const bool can_attempt_deflation =
706 sexpat_cov_func != nullptr && lik_gaussian != nullptr &&
707 !sexpat_cov_func->usesManifoldChart() &&
708 !sexpat_cov_func->usesGeodesicHeatKernel() && !principled_nugget_;
709 const bool placed =
710 covariance_valid && !distributed_covariance &&
712 geom, x, x_ind, C, /*include_noise=*/!can_attempt_deflation);
713 if (!covariance_valid || (!distributed_covariance && !placed &&
715 geom, x, x_ind, C, /*serial_per_rank=*/false,
716 /*include_constant=*/false,
717 /*include_noise=*/!can_attempt_deflation))) {
718 if (profile_energy_split) {
719 const double covariance_seconds =
720 reduce_max_seconds(elapsed_seconds(covariance_start));
721 recordEnergyProfileSplit(covariance_seconds, 0.0, 0.0);
722 }
723 return std::numeric_limits<double>::quiet_NaN();
724 }
725 Eigen::VectorXd factor_constant = constant_update;
726 if (distributed_covariance) {
727 C.resize(0, 0);
728 } else {
729 if (!placed && hasTrainingPermutation())
731 if (!can_attempt_deflation) {
732 if (jitter_sigma2 > 0.) C.diagonal().array() += jitter_sigma2;
733 if (use_correction_) {
734 const double K_sum =
735 C.diagonal().sum() + constant_update.squaredNorm();
736 const Eigen::Index n_ind = C.rows();
737 const double denom =
738 1.0 / correction_eps_ - static_cast<double>(n_ind * n_ind);
739 if (std::abs(denom) > 1e-30) {
740 const double corr = K_sum * K_sum / denom;
741 C.diagonal().array() += corr;
742 }
743 }
744 const EigenMatrix x_ordered =
746 const Eigen::VectorXd ind_ordered = permuteTrainingVector(x_ind);
747 const Eigen::VectorXd noise_ordered =
748 lik_gaussian != nullptr
749 ? lik_gaussian->evaluateTrainingVariance(x_ordered)
750 : Eigen::VectorXd::Zero(x_ordered.rows());
751 Eigen::VectorXd unused_constant;
752 (void)detail::prepareRigidDeflationState(
753 use_rigid_null_deflation_, /*factor_order=*/true, atoms_config,
754 x_ordered, ind_ordered, noise_ordered, jitter_sigma2,
755 /*unsupported_kernel_or_likelihood=*/true, rigid_deflation_,
757 rigid_deflation_.reset();
758 factor_constant = constant_update;
759 } else {
760 const EigenMatrix x_ordered =
762 const Eigen::VectorXd ind_ordered = permuteTrainingVector(x_ind);
763 const Eigen::VectorXd noise_ordered =
764 lik_gaussian != nullptr
765 ? lik_gaussian->evaluateTrainingVariance(x_ordered)
766 : Eigen::VectorXd::Zero(x_ordered.rows());
767 double corr = 0.0;
768 if (use_correction_) {
769 const double K_sum =
770 C.diagonal().sum() + noise_ordered.sum() +
771 static_cast<double>(C.rows()) * jitter_sigma2 +
772 constant_update.squaredNorm();
773 const Eigen::Index n_ind = C.rows();
774 const double denom =
775 1.0 / correction_eps_ - static_cast<double>(n_ind * n_ind);
776 if (std::abs(denom) > 1e-30) corr = K_sum * K_sum / denom;
777 }
778 const double extra_uniform = jitter_sigma2 + corr;
779 const bool maybe_krylov =
780 !use_hssvd_backend_ &&
783 krylov_objective_.plan.order == C.rows() &&
784 krylov_objective_.plan.krylov));
785 if (maybe_krylov ||
787 x_ordered, ind_ordered, noise_ordered, extra_uniform, C,
788 constant_update, factor_constant, /*factor_order=*/true)) {
789 C.diagonal() += noise_ordered;
790 if (extra_uniform != 0.0) C.diagonal().array() += extra_uniform;
791 factor_constant = constant_update;
792 }
793 }
794 }
795 const double covariance_seconds =
796 profile_energy_split
797 ? reduce_max_seconds(elapsed_seconds(covariance_start))
798 : 0.0;
799
800 const bool trace_dense_fit = report_level >= 3 && mpiContext().nprocs == 1;
801 std::uint64_t covariance_fingerprint = 0;
802 if (trace_dense_fit) {
803 traceFitKernelArguments(geom.pair_local,
804 sexpat_cov_func->combineParameters());
805#ifdef GPR_LINALG_SCALAPACK
806 if (distributed_covariance)
807 covariance_fingerprint = fitComponentFingerprint(
808 covariance_owned.data(), covariance_owned.size());
809 else
810#endif
811 covariance_fingerprint =
812 fitComponentFingerprint(C.data(), C.size());
813 }
814
815 if (use_hssvd_backend_ && use_hssvd_objective_contractions_ &&
816 !use_correction_ &&
817 (distributed_covariance ||
818 (C.rows() == C.cols() && C.rows() == activeFactorOrder(y.size())))) {
819 const double total_sigma2 =
820 (lik_gaussian ? lik_gaussian->getSigma2() : 0.0) + jitter_sigma2;
821 if (total_sigma2 > 0.0) {
822 const auto hssvd_start = std::chrono::steady_clock::now();
823
824 // The objective and gradient share the Cholesky reduction of C.
825 // The diagnostic eigenbasis is materialized only on request.
826#ifdef GPR_LINALG_SCALAPACK
827 auto& st_obj = backend().distributed();
828 st_obj.invalidate_L();
829 st_obj.invalidate_inv();
830 training_cholesky_is_distributed_ = false;
831#endif
832 // Retain diagnostic input in the same distributed layout as
833 // the factor. Normal objective and gradient calls need no gather.
834#ifdef GPR_LINALG_SCALAPACK
835 std::vector<double> pending_owned;
836 if (distributed_covariance) pending_owned = covariance_owned;
837#endif
838 const bool chol_ok =
839#ifdef GPR_LINALG_SCALAPACK
840 (distributed_covariance
841 ? backend().cholesky_distributed(
842 std::move(covariance_owned), covariance_descriptor,
843 static_cast<int>(x.rows()), L)
844 : backend().cholesky(C, L)) &&
845 backend().cholesky_rank_update(L, factor_constant);
846#else
848 backend(), C, factor_constant, L);
849#endif
850#ifdef GPR_LINALG_KOKKOS
851 // Host versus device retention is decided in
852 // retainTrainingCholeskyFactor. A failed factor must release the
853 // device posterior as well: clearing only the resident pointer
854 // leaves hasTrainingCholeskyFactor to dereference it.
855 if (chol_ok)
857 else
859#endif
860 double obj_cnorm = (report_level >= 3) ? C.norm() : 0.0;
861#ifdef GPR_LINALG_SCALAPACK
862 if (distributed_covariance && report_level >= 3) {
863 double norm_squared = 0.0;
864 const int order = static_cast<int>(x.rows());
865 for (int col = 0; col < st_obj.local_cols(order); ++col) {
866 const int j = st_obj.global_index_for_local(
867 col, st_obj.block_size(), st_obj.mycol(),
868 st_obj.npcol());
869 for (int row = 0; row < st_obj.local_rows(order); ++row) {
870 const int i = st_obj.global_index_for_local(
871 row, st_obj.block_size(), st_obj.myrow(),
872 st_obj.nprow());
873 if (i < j) continue;
874 const double value =
875 pending_owned[row + static_cast<std::size_t>(col) *
876 covariance_descriptor[8]];
877 norm_squared += (i == j ? 1.0 : 2.0) * value * value;
878 }
879 }
880 backend().ordered_sum_bcast(&norm_squared, 1);
881 obj_cnorm = std::sqrt(norm_squared);
882 }
883#endif
884 if (chol_ok) {
885 const bool permuted_factor_layout =
887 static_cast<Eigen::Index>(
888 training_permutation_.perm.size()) == y.size();
889 const Eigen::VectorXd y_factor =
890 permuted_factor_layout ? permuteTrainingVector(y) : y;
891 const bool deflated_obj =
892 rigid_deflation_.isActiveForFullOrder(y_factor.size());
893 if (deflated_obj) {
894 rigid_deflation_.updateTargetStats(y_factor);
895 }
896 // b = L^{-1} y, alpha = L^{-T} b, logdet = 2 sum log diag(L);
897 // identical reduction to the Cholesky-backend objective.
898 const auto solver = trainingSolver();
899 const Eigen::VectorXd b_obj = solver.whiten(
900 deflated_obj ? rigid_deflation_.projectVector(y_factor)
901 : y_factor);
902 Eigen::VectorXd alpha_factor = solver.unwhiten(b_obj);
903 if (deflated_obj) {
904 alpha_factor =
905 rigid_deflation_.liftVectorZeroRigid(alpha_factor);
906 }
907 const Eigen::VectorXd alpha =
908 permuted_factor_layout
909 ? gpr::unpermuteVector(alpha_factor,
911 : alpha_factor;
912 const double quad = b_obj.dot(b_obj);
913 const double logdet = solver.logDeterminant();
914 if (alpha.size() == y.size() && std::isfinite(logdet) &&
915 alpha.allFinite()) {
916#ifdef GPR_LINALG_SCALAPACK
917 if (distributed_covariance) {
918 const int order = static_cast<int>(x.rows());
919 for (int col = 0; col < st_obj.local_cols(order);
920 ++col) {
921 const int j = st_obj.global_index_for_local(
922 col, st_obj.block_size(), st_obj.mycol(),
923 st_obj.npcol());
924 for (int row = 0; row < st_obj.local_rows(order);
925 ++row) {
926 const int i = st_obj.global_index_for_local(
927 row, st_obj.block_size(), st_obj.myrow(),
928 st_obj.nprow());
929 if (i >= j)
930 pending_owned
931 [row + static_cast<std::size_t>(col) *
932 covariance_descriptor[8]] +=
933 constant_update(i) * constant_update(j);
934 }
935 }
936 hssvd_objective_pending_owned_ =
937 std::move(pending_owned);
938 std::copy_n(
939 covariance_descriptor, 9,
940 hssvd_objective_pending_descriptor_.begin());
941 } else
942#endif
943 if (!deflated_obj) {
944 C.noalias() +=
945 constant_update * constant_update.transpose();
946 hssvd_objective_pending_covariance_ = std::move(C);
947 } else {
948 clearHssvdPendingCovariance();
949 }
950 hssvd_objective_pending_permutation_ =
951 permuted_factor_layout ? training_permutation_
952 : StructuredPermutation{};
953 hssvd_objective_pending_noise_ = total_sigma2;
954 hssvd_objective_pending_lapack_rrr_ =
955 hssvd_dual_lapack_rrr_;
956 hssvd_objective_alpha_ = alpha;
957 hssvd_objective_trace_inv_noise_ = 1.0 / total_sigma2;
958 hssvd_objective_trace_direct_inverse_ = false;
959 hssvd_objective_basis_valid_ = true;
960 stampHssvdObjective();
961 // Drive the gradient trace from the cached Cholesky factor.
962 hssvd_objective_trace_via_cholesky_ = true;
963 b = b_obj;
964 recordHyperparameterDataTerm(static_cast<double>(y.size()),
965 quad);
967#ifdef GPR_LINALG_SCALAPACK
968 if (chol_ok) {
969 C.resize(0, 0);
970 st_obj.claim_cached_L(this);
971 training_cholesky_is_distributed_ = true;
972 }
973#else
974 C.resize(0, 0);
975#endif
977
978 const Index_t n = deflated_obj
979 ? static_cast<Index_t>(
980 rigid_deflation_.deflated_rows)
981 : static_cast<Index_t>(x.rows());
982 if (report_level >= 3) {
983 static int obj_dbg = 0;
984 if (obj_dbg++ < 14) {
985 int rk = 0;
986 int np = 1;
987#ifdef GPR_LINALG_SCALAPACK
988 int mpi_initialized = 0;
989 MPI_Initialized(&mpi_initialized);
990 if (mpi_initialized) {
991 MPI_Comm_rank(mpiContext().comm, &rk);
992 MPI_Comm_size(mpiContext().comm, &np);
993 }
994#endif
995 if (rk == 0)
996 std::fprintf(
997 stderr,
998 "[OBJ] np=%d n=%lld ynorm=%.17g "
999 "Cnorm=%.17g logdet=%.17g quad=%.17g\n",
1000 np, (long long)n, y.norm(), obj_cnorm,
1001 logdet, quad);
1002 }
1003 }
1004 const double edata =
1005 0.5 * static_cast<double>(n) *
1006 numerics::log(2.0 * M_PI) +
1007 0.5 * logdet + 0.5 * quad +
1008 (deflated_obj ? rigid_deflation_.nlmlPenalty() : 0.0);
1009 double eprior = 0.0;
1010 if (const_cov_fun) {
1011 eprior -= const_cov_fun->calculateLogPrior();
1012 }
1013 if (sexpat_cov_func)
1014 eprior -= sexpat_cov_func->calculateLogPrior();
1015 if (lik_gaussian) {
1016 eprior -= lik_gaussian->evaluateLogPrior();
1017 }
1018 if (profile_energy_split) {
1019 const double hssvd_seconds =
1020 reduce_max_seconds(elapsed_seconds(hssvd_start));
1021 recordEnergyProfileSplit(covariance_seconds,
1022 hssvd_seconds, 0.0);
1023 }
1024 return edata + eprior;
1025 }
1026 }
1027#ifdef GPR_LINALG_SCALAPACK
1028 if (distributed_covariance)
1029 covariance_owned = std::move(pending_owned);
1030#endif
1031 }
1032 }
1033
1034 krylov_objective_.solver.reset();
1035 krylov_objective_.covariance.reset();
1036#ifndef GPR_LINALG_SCALAPACK
1037 if (const auto krylov_data =
1038 evaluateKrylovObjective(constant_update, x, y)) {
1039 double eprior = 0.0;
1040 if (const_cov_fun) eprior -= const_cov_fun->calculateLogPrior();
1041 if (sexpat_cov_func) eprior -= sexpat_cov_func->calculateLogPrior();
1042 if (lik_gaussian) eprior -= lik_gaussian->evaluateLogPrior();
1044 return *krylov_data + eprior;
1045 }
1046#endif
1047 const auto cholesky_start = std::chrono::steady_clock::now();
1048#ifdef GPR_LINALG_SCALAPACK
1049 auto& st = backend().distributed();
1050 st.invalidate_L();
1051 st.invalidate_inv();
1052 training_cholesky_is_distributed_ = false;
1054 (distributed_covariance
1055 ? backend().cholesky_distributed(std::move(covariance_owned),
1056 covariance_descriptor,
1057 static_cast<int>(x.rows()), L)
1058 : backend().cholesky(C, L)) &&
1059 backend().cholesky_rank_update(L, factor_constant);
1060#else
1062 backend(), C, factor_constant, L);
1063#endif
1064#ifdef GPR_LINALG_KOKKOS
1067 else
1069#endif
1070 if (is_decomposed_succesfully && !distributed_covariance)
1071 C.noalias() += factor_constant * factor_constant.transpose();
1072#ifdef GPR_LINALG_SCALAPACK
1074 C.resize(0, 0);
1075 st.claim_cached_L(this);
1076 training_cholesky_is_distributed_ = true;
1077 }
1078#endif
1080#ifdef GPR_LINALG_SCALAPACK
1081 training_cholesky_is_distributed_ = false;
1082#endif
1083 if (profile_energy_split) {
1084 const double cholesky_seconds =
1085 reduce_max_seconds(elapsed_seconds(cholesky_start));
1086 recordEnergyProfileSplit(covariance_seconds, cholesky_seconds, 0.0);
1087 }
1088 return std::numeric_limits<double>::quiet_NaN();
1089 }
1090 const double cholesky_seconds =
1091 profile_energy_split
1092 ? reduce_max_seconds(elapsed_seconds(cholesky_start))
1093 : 0.0;
1094
1095 const auto posterior_start = std::chrono::steady_clock::now();
1097#ifndef GPR_LINALG_SCALAPACK
1100#endif
1101
1102 const Index_t n = rigid_deflation_.isActiveForFullOrder(x.rows())
1103 ? static_cast<Index_t>(rigid_deflation_.deflated_rows)
1104 : static_cast<Index_t>(x.rows());
1105 const double zc = trainingSolver().halfLogDeterminant();
1106 double edata = 0.5 * n * numerics::log(2.0 * M_PI) + zc + 0.5 * b.dot(b);
1107 if (rigid_deflation_.isActiveForFullOrder(x.rows())) {
1108 edata += rigid_deflation_.nlmlPenalty();
1109 }
1110 double eprior = 0.0;
1111 if (const_cov_fun) eprior -= const_cov_fun->calculateLogPrior();
1112 if (sexpat_cov_func) eprior -= sexpat_cov_func->calculateLogPrior();
1113 if (lik_gaussian) eprior -= lik_gaussian->evaluateLogPrior();
1114 if (trace_dense_fit) {
1115 std::uint64_t factor_fingerprint = 0;
1116#ifdef GPR_LINALG_SCALAPACK
1117 if (training_cholesky_is_distributed_ && st.has_cached_L())
1118 factor_fingerprint = fitComponentFingerprint(
1119 st.cached_L(), static_cast<std::size_t>(st.cached_L_desc()[8]) *
1120 st.local_cols(st.cached_n()));
1121 else
1122#endif
1123 factor_fingerprint = fitComponentFingerprint(L.data(), L.size());
1124 std::fprintf(
1125 stderr,
1126 "[map-objective] n=%lld covariance=%016llx constant=%016llx "
1127 "factor=%016llx data=%016llx solution=%016llx "
1128 "logdet_half=%.17g quadratic=%.17g prior=%.17g\n",
1129 static_cast<long long>(n),
1130 static_cast<unsigned long long>(covariance_fingerprint),
1131 static_cast<unsigned long long>(fitComponentFingerprint(
1132 constant_update.data(), constant_update.size())),
1133 static_cast<unsigned long long>(factor_fingerprint),
1134 static_cast<unsigned long long>(
1135 fitComponentFingerprint(y.data(), y.size())),
1136 static_cast<unsigned long long>(
1137 fitComponentFingerprint(b.data(), b.size())),
1138 zc, b.dot(b), eprior);
1139 }
1141 if (profile_energy_split) {
1142 const double posterior_seconds =
1143 reduce_max_seconds(elapsed_seconds(posterior_start));
1144 recordEnergyProfileSplit(covariance_seconds, cholesky_seconds,
1145 posterior_seconds);
1146 }
1147 return edata + eprior;
1148}
void planObjectiveBackend(const EigenMatrix &x, const Eigen::VectorXd &y)
Update the plan from the dense factor just formed at this order.
bool evaluateTrainingCovarianceInFactorOrderFromGeometry(const TrainingKernelGeometry &geom, const EigenMatrix &x, const Eigen::VectorXd &x_ind, EigenMatrix &cov_matrix, bool include_noise=true)
std::optional< double > evaluateKrylovObjective(const Eigen::VectorXd &constant_update, const EigenMatrix &x, const Eigen::VectorXd &y)
bool cholesky(const EigenMatrix &C, EigenMatrix &L)
bool cholesky_rank_update(EigenMatrix &lower, const Eigen::VectorXd &vector)
bool mpi_initialized()
Definition gpridge.hpp:2789
static double curvature_seconds

◆ evaluateEnergyLocalOnly()

double gpr::GaussianProcessRegression::evaluateEnergyLocalOnly ( const Eigen::VectorXd & w,
const EigenMatrix & x,
const Eigen::VectorXd & x_ind,
const Eigen::VectorXd & y )
protected

Definition at line 2351 of file GaussianProcessRegression.cpp.

2354{
2355 if (!detail::logParametersAreRepresentable(w)) {
2356 return std::numeric_limits<double>::infinity();
2357 }
2358 setParameters(w);
2359
2360 const Eigen::Index n = x.rows();
2361 if (n <= 0 || y.rows() != n) {
2362 return std::numeric_limits<double>::quiet_NaN();
2363 }
2364
2365 EigenMatrix C_local;
2366 evaluateTrainingCovarianceMatrix(x, x_ind, C_local,
2367 /*serial_per_rank=*/true);
2368 if (jitter_sigma2 > 0.0) C_local.diagonal().array() += jitter_sigma2;
2369
2370 Eigen::LLT<EigenMatrix> llt(C_local);
2371 if (llt.info() != Eigen::Success) {
2372 return std::numeric_limits<double>::quiet_NaN();
2373 }
2374
2375 const auto& matrix_llt = llt.matrixLLT();
2376 const auto lower = matrix_llt.template triangularView<Eigen::Lower>();
2377 const Eigen::VectorXd b_local = lower.solve(y);
2378 const double y_dot_alpha = b_local.squaredNorm();
2379 const double log_det = 2.0 * matrix_llt.diagonal().array().log().sum();
2380
2381 const double e_data =
2382 0.5 * (static_cast<double>(n) * numerics::log(2.0 * M_PI) + log_det +
2383 y_dot_alpha);
2384 double e_prior = 0.0;
2385 if (const_cov_fun) e_prior -= const_cov_fun->calculateLogPrior();
2386 if (sexpat_cov_func) e_prior -= sexpat_cov_func->calculateLogPrior();
2387 if (lik_gaussian) e_prior -= lik_gaussian->evaluateLogPrior();
2388
2389 const double energy = e_data + e_prior;
2390 return std::isfinite(energy) ? energy
2391 : std::numeric_limits<double>::quiet_NaN();
2392}

◆ evaluateGradient()

void gpr::GaussianProcessRegression::evaluateGradient ( const EigenMatrix & x,
const Eigen::VectorXd & x_ind,
const Eigen::VectorXd & y,
Eigen::VectorXd & gradient )
protectedvirtual

Evaluate the gradient of energy (GP_E) for Gaussian Process.

This function takes a full GP parameter vector W, GP structure GP, a matrix X of input vectors and a matrix Y of target vectors, and evaluates the gradient G of the energy function (gp_e). Each row of X corresponds to one input vector and each row of Y corresponds to one target vector.

Parameters
xMatrix of coordinates
x_indPer-row observation type or derivative-channel indices
yVector of energy and gradients
gradientCalculated new gradient

Definition at line 2008 of file EnergyGradient.cpp.

2012{
2013 // Both objective entry points use the same derivative assembly. A local
2014 // handle follows the current atom configuration and observation indices.
2015#ifdef GPR_LINALG_KOKKOS
2016 if (devicePosteriorGradient(gradient)) return;
2017#endif
2018 TrainingKernelGeometry geometry;
2019 const TrainingKernelGeometry* handle = nullptr;
2020 if (use_training_geometry_handle_) {
2021 // Distances do not depend on theta. The fit's first evaluation
2022 // builds them; the gradient at that same theta applies them.
2023 handle = fitGeometryFor(x, x_ind);
2024 if (handle == nullptr &&
2025 prepareTrainingKernelGeometry(x, x_ind, geometry,
2026 /*reused=*/true)) {
2027 handle = &geometry;
2028 }
2029 }
2030 evaluateGradientWithGeometry(x, x_ind, y, gradient, handle);
2031}
bool devicePosteriorGradient(Eigen::VectorXd &gradient)

◆ evaluateGradientAfterEnergy()

bool gpr::GaussianProcessRegression::evaluateGradientAfterEnergy ( const Eigen::VectorXd & w,
const EigenMatrix & x,
const Eigen::VectorXd & x_ind,
const Eigen::VectorXd & y,
Eigen::VectorXd & gradient )
nodiscard

Gradient at the theta whose factor and kernel evaluateEnergy just built. A mismatched theta returns false so the caller recomputes both.

Definition at line 395 of file EnergyGradient.cpp.

399{
400 if (hyperparameter_objective_mode_ == HyperparameterObjectiveMode::LOO ||
401 hyperparameter_objective_mode_ ==
403 return false;
404 }
405 if (last_objective_theta_.size() != w.size() ||
406 last_objective_theta_ != w || !is_decomposed_succesfully ||
407 !is_training_cov_matrix_evaluated || y.size() != x.rows()) {
408 return false;
409 }
410#ifndef GPR_LINALG_SCALAPACK
411#ifdef GPR_LINALG_KOKKOS
412 if (!hasDevicePosterior())
413#endif
414 if (L.rows() != activeFactorOrder(y.size()) ||
415 L.cols() != activeFactorOrder(y.size()))
416 return false;
417#endif
418 gradient.resize(w.size());
419 evaluateGradient(x, x_ind, y, gradient);
420 return gradient.size() == w.size() && gradient.allFinite();
421}

◆ evaluateGradientAfterEnergyFromGeometry()

bool gpr::GaussianProcessRegression::evaluateGradientAfterEnergyFromGeometry ( const Eigen::VectorXd & w,
const TrainingKernelGeometry & geom,
const EigenMatrix & x,
const Eigen::VectorXd & x_ind,
const Eigen::VectorXd & y,
Eigen::VectorXd & gradient )
nodiscard

Definition at line 1196 of file EnergyGradient.cpp.

1200{
1201 if (hyperparameter_objective_mode_ == HyperparameterObjectiveMode::LOO ||
1202 hyperparameter_objective_mode_ ==
1204 return false;
1205 }
1206 gradient.resize(w.size());
1207 evaluateGradientWithGeometry(x, x_ind, y, gradient, &geom);
1208 return gradient.size() == w.size() && gradient.allFinite();
1209}

◆ evaluateGradientWithGeometry()

void gpr::GaussianProcessRegression::evaluateGradientWithGeometry ( const EigenMatrix & x,
const Eigen::VectorXd & x_ind,
const Eigen::VectorXd & y,
Eigen::VectorXd & gradient,
const TrainingKernelGeometry * training_geom )
protected

Definition at line 2033 of file EnergyGradient.cpp.

2037{
2038 gradient_replicated_inverse_entries_for_testing_ = 0;
2039#ifdef GPR_LINALG_KOKKOS
2040 if (devicePosteriorGradient(gradient)) return;
2041#endif
2042 const bool profile_gradient_split = profile_gradient_split_;
2043 auto reduce_max_seconds = [&](const double local_seconds) {
2044#ifdef GPR_LINALG_SCALAPACK
2045 int mpi_up = 0;
2046 MPI_Initialized(&mpi_up);
2047 if (!mpi_up) return local_seconds;
2048
2049 int nprocs = 1;
2050 MPI_Comm_size(mpiContext().comm, &nprocs);
2051 if (nprocs == 1) return local_seconds;
2052
2053 const double send_seconds = local_seconds;
2054 double global_seconds = 0.0;
2055 MPI_Allreduce(&send_seconds, &global_seconds, 1, MPI_DOUBLE, MPI_MAX,
2056 mpiContext().comm);
2057 return global_seconds;
2058#else
2059 return local_seconds;
2060#endif
2061 };
2062 auto elapsed_seconds =
2063 [&](const std::chrono::steady_clock::time_point& start) {
2064 return std::chrono::duration<double>(
2065 std::chrono::steady_clock::now() - start)
2066 .count();
2067 };
2068
2069 EigenMatrix invC;
2070 Eigen::VectorXd alpha;
2071 Eigen::VectorXd uDdim;
2072 FieldMatrixd gdata;
2073 FieldMatrixd gprior;
2074
2075 // Note: the calculateTrainingCovarianceMatrix() method is always called in
2076 // the evaluateEnergy() method, and we always call for the
2077 // evaluateGradient() method after evaluateEnergy() being called (see
2078 // evaluateEnergyAndGradient(). So, there is no point to re-evaluate
2079 // covariance metrix here. However, we keep it hear guarded by an
2080 // if-statement for sake of unit tests. Otherwise, the matrix C will not be
2081 // allocated.
2087 }
2088
2089 const double hssvd_likelihood_sigma2 =
2090 lik_gaussian ? lik_gaussian->getSigma2() : 0.0;
2091 const double hssvd_total_sigma2 = hssvd_likelihood_sigma2 + jitter_sigma2;
2092 // The objective trace state can be active either as the orthonormal
2093 // Q-form contraction (use_hssvd_gradient) or, when the objective kept the
2094 // canonical Cholesky factor, through that factor exactly like the Cholesky
2095 // backend (hssvd_objective_trace_via_cholesky_). The latter keeps the
2096 // gradient bit-consistent with the reference; the eigenbasis markers stay
2097 // valid for diagnostics either way.
2098 const bool hssvd_objective_active =
2099 use_hssvd_backend_ && use_hssvd_objective_contractions_ &&
2100 hssvdObjectiveStampMatches() &&
2101 hssvd_objective_trace_basis_.rows() == y.size() &&
2102 hssvd_objective_trace_weighted_basis_.rows() == y.size() &&
2103 hssvd_objective_trace_basis_.cols() ==
2104 hssvd_objective_trace_weighted_basis_.cols() &&
2105 hssvd_objective_alpha_.size() == y.size() && hssvd_total_sigma2 > 0.0;
2106 const bool use_hssvd_gradient =
2107 hssvd_objective_active && !hssvd_objective_trace_via_cholesky_;
2108
2109#ifndef GPR_LINALG_SCALAPACK
2110 const auto& krylov = krylov_objective_.solver;
2111 if (!use_hssvd_gradient && krylov &&
2112 krylov_objective_.y.size() == y.size() && krylov_objective_.y == y &&
2114 evaluateKrylovGradient(x, x_ind, gradient, training_geom);
2115 return;
2116 }
2117 if (!use_hssvd_gradient && L.rows() != activeFactorOrder(y.rows()))
2119#endif
2120 if (!use_hssvd_gradient && b.rows() != activeFactorOrder(y.rows())) {
2122 }
2123
2124 const auto alpha_start = std::chrono::steady_clock::now();
2125 if (use_hssvd_gradient) {
2126 alpha = hssvd_objective_alpha_;
2127 hssvd_trace_basis_ = &hssvd_objective_trace_basis_;
2128 hssvd_trace_weighted_basis_ = &hssvd_objective_trace_weighted_basis_;
2129 hssvd_trace_inv_noise_ = hssvd_objective_trace_inv_noise_;
2130 hssvd_trace_direct_inverse_ = hssvd_objective_trace_direct_inverse_;
2131 } else {
2132 // Keep the SCG algebra in terms of the Cholesky factor and solves:
2133 // alpha = C^{-1} y is obtained as alpha = L^{-T} (L^{-1} y).
2134 alpha = trainingSolver().unwhiten(b);
2135 if (rigid_deflation_.isActiveForFullOrder(y.rows()) &&
2136 alpha.size() == rigid_deflation_.deflated_rows) {
2137 alpha = rigid_deflation_.liftVectorZeroRigid(alpha);
2138 }
2139 }
2140 const double alpha_seconds =
2141 profile_gradient_split
2142 ? reduce_max_seconds(elapsed_seconds(alpha_start))
2143 : 0.0;
2144
2145 double inverse_seconds = 0.0;
2146#ifdef GPR_LINALG_SCALAPACK
2147 auto& st = backend().distributed();
2148 if (!use_hssvd_gradient) {
2149 gpr::assertMsg(
2150 st.has_cached_L() && st.cached_n() == static_cast<int>(x.rows()),
2151 "ScaLAPACK gradient path requires the active distributed "
2152 "Cholesky factor");
2153 }
2154#endif
2155
2156 // The dense gradient does not replicate K^{-1}. Trace terms solve
2157 // against dK, so two factors of the same Gram do not each grow their
2158 // own inverse by cond(K) * eps.
2159 gradient_replicated_inverse_entries_for_testing_ = 0;
2160 if (!use_hssvd_gradient && hasTrainingPermutation()) {
2161#ifndef GPR_LINALG_SCALAPACK
2163#endif
2164 }
2165
2166 if (const double data_term_scale = hyperparameterDataTermScale();
2167 data_term_scale != 1.0)
2168 alpha *= std::sqrt(data_term_scale);
2169
2170 // Gradient with respect to covariance function parameters
2171 extractUniqueIndices(x_ind, uDdim);
2172
2173 // Hutchinson stochastic-trace estimator for the hyperparameter-gradient
2174 // trace term tr(K^-1 dK), controlled by the config field hutch_num_probes_
2175 // (setHutchinsonProbes; default 0 = off, exact). m Rademacher probes z_j
2176 // with w_j = K^-1 z_j;
2177 // accumulateBlockContribution estimates the trace from {w_j, z_j} instead
2178 // of contracting the full dense inverse, leaving the quadratic (alpha-K)
2179 // term exact. Fixed seed so SCG sees a deterministic gradient surrogate
2180 // across NLML evaluations. w_j = K^{-1} z_j is a solve against the
2181 // factor, in observation order. The distributed path keeps its own trace.
2182 EigenMatrix hutch_Z, hutch_W;
2183 {
2184 const int hutch_m = hutch_num_probes_;
2185 if (!use_hssvd_gradient && hutch_m > 0 &&
2186 L.rows() == activeFactorOrder(y.size()) &&
2187 L.cols() == activeFactorOrder(y.size())) {
2188 const Eigen::Index N = y.size();
2189 std::mt19937 rng(0x9E3779B9u);
2190 hutch_Z.resize(N, hutch_m);
2191 for (Eigen::Index a = 0; a < N; ++a)
2192 for (int j = 0; j < hutch_m; ++j)
2193 hutch_Z(a, j) = (rng() & 1u) ? 1.0 : -1.0;
2194 const EigenMatrix Z_factor =
2197 : hutch_Z;
2198 EigenMatrix W_factor;
2199 if (rigid_deflation_.isActiveForFullOrder(N)) {
2200 const EigenMatrix Z_r = rigid_deflation_.projectRows(Z_factor);
2203 W_factor = rigid_deflation_.liftSolvedColumns(Z_factor, W_r);
2204 } else {
2205 W_factor = linalg::back_solve_mat(
2206 L, linalg::forward_solve_mat(L, Z_factor));
2207 }
2208 hutch_W =
2211 : W_factor;
2212 hutch_trace_W_ = &hutch_W;
2213 hutch_trace_Z_ = &hutch_Z;
2214 }
2215 }
2216
2217 // Surrogate fits take tr(K^{-1} dK) from a solve, so two factors of one
2218 // Gram do not each grow an inverse by cond(K) * eps. That is the
2219 // OCINEB curvature. The prior-free marginal-likelihood fit was measured
2220 // on the explicit inverse: the solve disagrees by about that cond(K) *
2221 // eps, and this fit then stops one step early (27 against the measured
2222 // 28). Eigen forms that inverse again for the prior-free fit only.
2223 // CHOLMOD's solve already takes the measured number of steps.
2224 // ScaLAPACK and SLATE take the trace from the distributed factor and
2225 // never read this inverse.
2226 const bool prior_free_inverse = priorFreeReplicatedInverse(
2227#ifdef GPR_LINALG_CHOLMOD
2228 true,
2229#else
2230 false,
2231#endif
2233 true,
2234#else
2235 false,
2236#endif
2237#ifdef GPR_LINALG_SLATE
2238 true,
2239#else
2240 false,
2241#endif
2242 unregularized_marginal_likelihood_, use_hssvd_gradient);
2243 const bool deflated_grad =
2244 !use_hssvd_gradient && rigid_deflation_.isActiveForFullOrder(y.size());
2245 if (prior_free_inverse) {
2246 invC = trainingSolver().inverse();
2247 if (deflated_grad) {
2248 invC = rigid_deflation_.liftInverse(invC);
2249 }
2252 gradient_replicated_inverse_entries_for_testing_ =
2253 static_cast<std::size_t>(invC.size());
2254 }
2255#ifdef GPR_LINALG_SCALAPACK
2256 const bool distributed_factor = training_cholesky_is_distributed_;
2257#else
2258 constexpr bool distributed_factor = false;
2259#endif
2260 const EigenMatrix* trace_factor = nullptr;
2262 prior_free_inverse, use_hssvd_gradient, distributed_factor,
2263 static_cast<long long>(L.rows()), static_cast<long long>(L.cols()),
2264 static_cast<long long>(activeFactorOrder(y.size())))) {
2265 trace_factor = &L;
2266 }
2267
2268 const auto const_start = std::chrono::steady_clock::now();
2269 const double inverse_before_const = PhaseTimers::gradient_inverse_seconds;
2270 calculateGradientWithCovFunc(
2271 x, x_ind, uDdim, alpha, invC, *const_cov_fun, gdata, gprior,
2272 /*serial_per_rank=*/use_hssvd_gradient, training_geom, trace_factor);
2273 const double const_inverse_seconds =
2274 PhaseTimers::gradient_inverse_seconds - inverse_before_const;
2275 const double const_seconds =
2276 profile_gradient_split
2277 ? reduce_max_seconds(std::max(
2278 0.0, elapsed_seconds(const_start) - const_inverse_seconds))
2279 : 0.0;
2280
2281 const auto sexpat_start = std::chrono::steady_clock::now();
2282 const double inverse_before_sexpat = PhaseTimers::gradient_inverse_seconds;
2283 calculateGradientWithCovFunc(
2284 x, x_ind, uDdim, alpha, invC, *sexpat_cov_func, gdata, gprior,
2285 /*serial_per_rank=*/use_hssvd_gradient, training_geom, trace_factor);
2286 hutch_trace_W_ = nullptr;
2287 hutch_trace_Z_ = nullptr;
2288 const double sexpat_inverse_seconds =
2289 PhaseTimers::gradient_inverse_seconds - inverse_before_sexpat;
2290 const double sexpat_seconds =
2291 profile_gradient_split
2292 ? reduce_max_seconds(std::max(
2293 0.0, elapsed_seconds(sexpat_start) - sexpat_inverse_seconds))
2294 : 0.0;
2295
2296 // Gradient with respect to Gaussian likelihood function parameters
2297 // Evaluate the gradient from Gaussian likelihood
2298 FieldMatrixd gprior_lik;
2299
2300#ifndef NDEBUG
2301 gpr::assertMsg(lik_gaussian != nullptr,
2302 "Object of Gausian likelihood is not allocated!");
2303#endif
2304 lik_gaussian->evaluateLogPriorGradient(gprior_lik);
2305
2306 if (gprior_lik.size() != 0) {
2307 gprior_lik *= -1.;
2308 gpr::field::appendRows(gprior, gprior_lik);
2309 }
2310
2311#ifdef GPR_LINALG_SCALAPACK
2312 const bool use_solve_based_trace = true;
2313#else
2314 constexpr bool use_solve_based_trace = false;
2315#endif
2316 // Use the same guarded trace_factor as the covariance derivatives: when
2317 // prior_free_inverse, use_hssvd_gradient, a distributed factor, or a
2318 // missing/mismatched factor leaves trace_factor null, passing an empty
2319 // matrix avoids stale L and selects invC.trace() or the distributed trace.
2320 const EigenMatrix no_factor;
2321 appendLikelihoodNoiseGradient(
2322 alpha, invC, trace_factor != nullptr ? *trace_factor : no_factor,
2323 use_solve_based_trace, gdata, gprior);
2324 hssvd_trace_basis_ = nullptr;
2325 hssvd_trace_weighted_basis_ = nullptr;
2326 hssvd_trace_inv_noise_ = 0.0;
2327 hssvd_trace_direct_inverse_ = false;
2328
2329 if (gprior.size() != 0) {
2330 if (gradient.rows() != gprior.size()) gradient.resize(gprior.size());
2331 gradient =
2332 Eigen::Map<const Eigen::VectorXd>(gdata.data(), gdata.size()) +
2333 Eigen::Map<const Eigen::VectorXd>(gprior.data(), gprior.size());
2334 }
2335
2336 if (report_level >= 3 && mpiContext().nprocs == 1) {
2337 const double* inverse_data = invC.data();
2338 std::size_t inverse_size = static_cast<std::size_t>(invC.size());
2339#ifdef GPR_LINALG_SCALAPACK
2340 if (st.has_cached_inv()) {
2341 inverse_data = st.cached_inv();
2342 inverse_size = static_cast<std::size_t>(st.cached_inv_desc()[8]) *
2343 st.local_cols(st.cached_inv_n());
2344 }
2345#endif
2346 std::fprintf(
2347 stderr,
2348 "[map-gradient] alpha=%016llx inverse=%016llx data=%016llx "
2349 "prior=%016llx result=%016llx\n",
2350 static_cast<unsigned long long>(
2351 fitComponentFingerprint(alpha.data(), alpha.size())),
2352 static_cast<unsigned long long>(
2353 fitComponentFingerprint(inverse_data, inverse_size)),
2354 static_cast<unsigned long long>(
2355 fitComponentFingerprint(gdata.data(), gdata.size())),
2356 static_cast<unsigned long long>(
2357 fitComponentFingerprint(gprior.data(), gprior.size())),
2358 static_cast<unsigned long long>(
2359 fitComponentFingerprint(gradient.data(), gradient.size())));
2360 }
2361
2362 if (profile_gradient_split) {
2363 inverse_seconds +=
2364 reduce_max_seconds(const_inverse_seconds + sexpat_inverse_seconds);
2365 recordGradientProfileSplit(alpha_seconds, inverse_seconds,
2366 const_seconds, sexpat_seconds);
2367 }
2368}
#define GPR_LINALG_SCALAPACK
Definition SlateBackend.h:9
void evaluateKrylovGradient(const EigenMatrix &x, const Eigen::VectorXd &x_ind, Eigen::VectorXd &gradient, const TrainingKernelGeometry *training_geom)
Eigen::VectorXd objectiveParameterStamp() const
virtual double hyperparameterDataTermScale() const
EigenMatrix back_solve_mat(const EigenMatrix &L, const EigenMatrix &B)
Back triangular solve with matrix RHS (BLAS equivalent: dtrsm with side=L, uplo=L,...
EigenMatrix forward_solve_mat(const EigenMatrix &L, const EigenMatrix &B)
Forward triangular solve with matrix RHS (BLAS equivalent: dtrsm).
EigenMatrix unpermuteSymmetricMatrix(const EigenMatrix &input, const StructuredPermutation &p)
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)
static double gradient_inverse_seconds

◆ evaluateHyperparameterObjectiveEnergyAndGradient()

void gpr::GaussianProcessRegression::evaluateHyperparameterObjectiveEnergyAndGradient ( const Eigen::VectorXd & w,
const EigenMatrix & x,
const Eigen::VectorXd & x_ind,
const Eigen::VectorXd & y,
EnergyAndGradient & energy_and_gradient )

Compute the cached objective-stationarity skip predicate: ||H^{-1} g_new||, where H is an observed-information Hessian at the reference theta and g_new is the augmented-set NLML gradient evaluated at that same theta. Laplace, slice/PSIS, and MAP/SCG Hessian caches can supply H. Returns +infinity when no usable Hessian cache is available. Predicted Newton shift ||H^-1 g_new|| at theta_reference. The optional outputs return the shift vector, the objective and its gradient at theta_reference, so a caller can take the step. Energy and gradient of the objective the hyperparameters are actually fitted on: the leave-one-out objectives (through the training-geometry handle) when they are selected, the marginal likelihood otherwise. The stationarity test that decides whether a refit can be skipped must read this gradient; reading the marginal likelihood's under a LOO fit reported a large shift at every outer iteration and forced a full SCG refit each time.

Definition at line 3672 of file Optimize.cpp.

3677{
3678 const bool loo =
3679 hyperparameter_objective_mode_ == HyperparameterObjectiveMode::LOO;
3680 const bool local_loo = hyperparameter_objective_mode_ ==
3682 if (loo || local_loo) {
3683 TrainingKernelGeometry geometry;
3685 use_training_geometry_handle_ &&
3686 prepareTrainingKernelGeometry(x, x_ind, geometry)) {
3687 if (loo) {
3689 w, geometry, x, x_ind, y, energy_and_gradient);
3690 } else {
3692 w, geometry, x, x_ind, y, energy_and_gradient);
3693 }
3694 return;
3695 }
3696 }
3698}
void evaluateEnergyAndGradient(const Eigen::VectorXd &w, const EigenMatrix &x, const Eigen::VectorXd &x_ind, const Eigen::VectorXd &y, EnergyAndGradient &energy_and_gradient)
Evaluate the energy function (un-normalized negative marginal log posterior) and its gradient.
void evaluateLeaveOneOutEnergyAndGradientFromGeometry(const Eigen::VectorXd &w, const TrainingKernelGeometry &geom, const EigenMatrix &x, const Eigen::VectorXd &x_ind, const Eigen::VectorXd &y, EnergyAndGradient &energy_and_gradient)

◆ evaluateKrylovGradient()

void gpr::GaussianProcessRegression::evaluateKrylovGradient ( const EigenMatrix & x,
const Eigen::VectorXd & x_ind,
Eigen::VectorXd & gradient,
const TrainingKernelGeometry * training_geom )
protected

Gradient at the Krylov objective's parameters: its weights for the quadratic terms and its probes for every trace.

Definition at line 155 of file KrylovObjective.cpp.

158{
159 const auto& solver = *krylov_objective_.solver;
160 Eigen::VectorXd alpha = unpermuteTrainingVector(solver.weights());
161 if (const double data_term_scale = hyperparameterDataTermScale();
162 data_term_scale != 1.0)
163 alpha *= std::sqrt(data_term_scale);
164 EigenMatrix W = solver.probeSolutions();
165 EigenMatrix Z = solver.probePreconditioned();
169 }
170 Eigen::VectorXd uDdim;
171 extractUniqueIndices(x_ind, uDdim);
172 FieldMatrixd gdata;
173 FieldMatrixd gprior;
174 const EigenMatrix no_inverse;
175 struct RestoreTrace {
176 const EigenMatrix*& weights;
177 const EigenMatrix*& probes;
178 const EigenMatrix* saved_weights;
179 const EigenMatrix* saved_probes;
180 ~RestoreTrace()
181 {
182 weights = saved_weights;
183 probes = saved_probes;
184 }
185 } restore{hutch_trace_W_, hutch_trace_Z_, hutch_trace_W_, hutch_trace_Z_};
186 hutch_trace_W_ = &W;
187 hutch_trace_Z_ = &Z;
188 calculateGradientWithCovFunc(x, x_ind, uDdim, alpha, no_inverse,
189 *const_cov_fun, gdata, gprior,
190 /*serial_per_rank=*/false, training_geom);
191 calculateGradientWithCovFunc(x, x_ind, uDdim, alpha, no_inverse,
192 *sexpat_cov_func, gdata, gprior,
193 /*serial_per_rank=*/false, training_geom);
194 FieldMatrixd gprior_lik;
195 lik_gaussian->evaluateLogPriorGradient(gprior_lik);
196 if (gprior_lik.size() != 0) {
197 gprior_lik *= -1.;
198 gpr::field::appendRows(gprior, gprior_lik);
199 }
200 appendLikelihoodNoiseGradient(alpha, no_inverse, no_inverse,
201 /*use_solve_based_trace=*/false, gdata,
202 gprior);
203 if (gprior.size() != 0) {
204 if (gradient.rows() != gprior.size()) gradient.resize(gprior.size());
205 gradient =
206 Eigen::Map<const Eigen::VectorXd>(gdata.data(), gdata.size()) +
207 Eigen::Map<const Eigen::VectorXd>(gprior.data(), gprior.size());
208 }
209}

◆ evaluateKrylovObjective()

std::optional< double > gpr::GaussianProcessRegression::evaluateKrylovObjective ( const Eigen::VectorXd & constant_update,
const EigenMatrix & x,
const Eigen::VectorXd & y )
nodiscardprotected

The objective's data term through the Krylov backend, or nothing when the plan or the budget hands it to the dense factor.

Definition at line 105 of file KrylovObjective.cpp.

108{
111 const Eigen::Index n = C.rows();
112 auto& plan = krylov_objective_.plan;
113 if (!forced && !(plan.order == n && plan.krylov)) return {};
114 if (n == 0 || C.cols() != n || y.size() != n) return {};
115 const auto added = krylovAddedDiagonal(x);
116 if (!added) return {};
117
118 auto covariance = std::make_shared<EigenMatrix>(C);
119 if (constant_update.size() == n)
120 covariance->noalias() += constant_update * constant_update.transpose();
121 auto op = std::make_shared<linalg::linop::DenseOperator>(*covariance);
122 auto solver =
123 std::make_shared<linalg::linop::KrylovCovarianceSolver>(op, *added);
124 linalg::linop::KrylovTolerances tolerances;
125 tolerances.objective = scg_opt_settings.common.tolerance_func;
126 tolerances.gradient = std::min(scg_opt_settings.common.tolerance_func,
127 scg_opt_settings.common.tolerance_sol);
128 tolerances.inverse_trace_weight = theta_includes_likelihood_noise_
130 : 0.0;
131 if (!(tolerances.objective > 0.0)) return {};
132 const Eigen::VectorXd y_factor = permuteTrainingVector(y);
133 const Eigen::Index rank =
134 forced ? krylov_objective_.forced_rank : plan.rank;
135 const double budget =
136 forced ? std::numeric_limits<double>::infinity() : plan.dense_flops;
137 if (!solver->prepare(y_factor, rank, tolerances, budget, kProbeSeed)) {
138 if (!forced) plan.krylov = false;
139 return {};
140 }
141 C = *covariance;
143 b.resize(0);
145 krylov_objective_.covariance = covariance;
146 krylov_objective_.solver = solver;
149 const double quadratic = solver->inverseQuadratic(y_factor);
150 recordHyperparameterDataTerm(static_cast<double>(n), quadratic);
151 return 0.5 * static_cast<double>(n) * numerics::log(2.0 * M_PI) +
152 0.5 * solver->logDeterminant() + 0.5 * quadratic;
153}
std::optional< Eigen::VectorXd > krylovAddedDiagonal(const EigenMatrix &x)

◆ evaluateLeaveOneOutEnergyAndGradientFromGeometry()

void gpr::GaussianProcessRegression::evaluateLeaveOneOutEnergyAndGradientFromGeometry ( const Eigen::VectorXd & w,
const TrainingKernelGeometry & geom,
const EigenMatrix & x,
const Eigen::VectorXd & x_ind,
const Eigen::VectorXd & y,
EnergyAndGradient & energy_and_gradient )

Definition at line 1211 of file EnergyGradient.cpp.

1216{
1217 if (detail::rejectInvalidHyperparameters(w, energy_and_gradient)) return;
1218 ++leave_one_out_objective_evaluations_for_testing_;
1219
1220 auto fail = [&]() {
1221 energy_and_gradient.energy = std::numeric_limits<double>::quiet_NaN();
1222 energy_and_gradient.gradient.resize(w.size());
1223 energy_and_gradient.gradient.setZero();
1224 };
1225
1226 setParameters(w);
1227 hssvd_objective_basis_valid_ = false;
1228 clearHssvdPendingCovariance();
1229 hssvd_objective_alpha_.resize(0);
1230 hssvd_objective_trace_basis_.resize(0, 0);
1231 hssvd_objective_trace_weighted_basis_.resize(0, 0);
1232 hssvd_objective_trace_inv_noise_ = 0.0;
1233 hssvd_objective_trace_direct_inverse_ = false;
1234 hssvd_objective_trace_via_cholesky_ = false;
1235
1236 if (!use_hssvd_backend_ || !use_hssvd_objective_contractions_) {
1237 fail();
1238 return;
1239 }
1240
1241 const detail::ObservationChannelLayout channels(x_ind);
1242 Coord geometry_positions;
1243 if (sexpat_cov_func == nullptr || y.size() != x.rows() ||
1244 x_ind.size() != x.rows() ||
1245 !extractGroupedGeometryPositions(
1246 x, channels, sexpat_cov_func->getConfInfo(), geometry_positions)) {
1247 fail();
1248 return;
1249 }
1250 const Eigen::Index n_geom = channels.rowsPerChannel();
1251
1253 EigenMatrix noisy_cov;
1255 geom, x, x_ind, noisy_cov, /*serial_per_rank=*/false)) {
1256 fail();
1257 return;
1258 }
1260 noisy_cov =
1262 if (jitter_sigma2 > 0.0) noisy_cov.diagonal().array() += jitter_sigma2;
1263 if (use_correction_) {
1264 const double K_sum = noisy_cov.diagonal().sum();
1265 const Eigen::Index n_ind = noisy_cov.rows();
1266 const double denom =
1267 1.0 / correction_eps_ - static_cast<double>(n_ind * n_ind);
1268 if (std::abs(denom) > 1e-30) {
1269 const double corr = K_sum * K_sum / denom;
1270 noisy_cov.diagonal().array() += corr;
1271 }
1272 }
1273
1274 const double total_sigma2 =
1275 (lik_gaussian ? lik_gaussian->getSigma2() : 0.0) + jitter_sigma2;
1276 if (!(total_sigma2 > 0.0) || noisy_cov.rows() != noisy_cov.cols() ||
1277 noisy_cov.rows() != y.size()) {
1278 fail();
1279 return;
1280 }
1281
1282 EigenMatrix kernel = noisy_cov;
1283 kernel.diagonal().array() -= total_sigma2;
1284 kernel = 0.5 * (kernel + kernel.transpose().eval());
1285
1286 StableBasisND loo_basis(backend_context_);
1287 // sqrt(eps) relative cutoff (NOT 0.0): a zero cutoff keeps singular modes
1288 // down to the float64 noise floor whose 1/S reinjection makes the LOO
1289 // objective depend on BLAS blocking (thread count), drifting the SCG theta
1290 // it feeds. sqrt(eps) drops only sub-precision noise and bounds the basis
1291 // condition at 1/sqrt(eps) = kappa_max, matching the dual-kernel cutoff in
1292 // factorizeStableBasisFromTraining; the colPivHouseholderQr solve is
1293 // rank-robust so the LOO residuals stay exact on the retained modes.
1294 const double loo_sv_rtol =
1295 std::sqrt(std::numeric_limits<double>::epsilon());
1296 loo_basis.factorizeKernel(kernel, /*sv_rtol=*/loo_sv_rtol,
1297 /*sv_abs_tol=*/0.0, /*sv_chop_tol=*/0.0);
1298 if (loo_basis.rank() <= 0 || loo_basis.numObs() != y.size()) {
1299 fail();
1300 return;
1301 }
1302
1303 const bool permuted_factor_layout =
1305 static_cast<Eigen::Index>(training_permutation_.perm.size()) ==
1306 y.size();
1307 const Eigen::VectorXd y_factor =
1308 permuted_factor_layout ? permuteTrainingVector(y) : y;
1309 const StableBasisPosteriorWeights weights =
1310 loo_basis.noisyPosteriorWeights(y_factor, total_sigma2);
1311 if (weights.alpha.size() != y.size() || !weights.alpha.allFinite()) {
1312 fail();
1313 return;
1314 }
1315
1316 const EigenMatrix& Q_factor = loo_basis.leftSingularVectors();
1317 const Eigen::ArrayXd s2 = loo_basis.singularValues().array().square();
1318 const Eigen::VectorXd shrink = (s2 / (s2 + total_sigma2)).matrix();
1319 const EigenMatrix Qshrink_factor = Q_factor * shrink.asDiagonal();
1320
1321 hssvd_objective_trace_basis_ =
1322 permuted_factor_layout
1324 : Q_factor;
1325 hssvd_objective_trace_weighted_basis_ =
1326 permuted_factor_layout
1328 : Qshrink_factor;
1329 hssvd_objective_alpha_ =
1330 permuted_factor_layout
1332 : weights.alpha;
1333 hssvd_objective_trace_inv_noise_ = 1.0 / total_sigma2;
1334 hssvd_objective_trace_direct_inverse_ = false;
1335 hssvd_objective_basis_valid_ = true;
1336 stampHssvdObjective();
1337
1338 const Eigen::Index n = y.size();
1339 // Per-geometry blocks contain every stored channel for one geometry.
1340 // Leaving out a whole geometry is the
1341 // correct derivative-GP LOO; a per-row LOO is blind to length-scale
1342 // collapse (same-geometry rows pin the held-out row), which lets ls -> 0
1343 // and blows up the dimer Hessian (~1/ls^4). The key is permuted into the
1344 // factor layout to match the basis rows.
1345 //
1346 // x_ind is NOT a geometry handle: it tags the derivative CHANNEL of a row
1347 // (0 = energy, 1..D = gradient component).
1348 // assembleMatrixOfRepetitiveCoordinates replicates the coordinate block
1349 // once per channel and assembleVectorFromEnergyAndGradient lays the
1350 // targets out channel-major (all energies, then all dE/dx, then dE/dy),
1351 // so rows sharing an x_ind value are one channel across EVERY geometry.
1352 // Grouping on it holds out a whole channel and leaves the remaining
1353 // channels at the held-out geometry in the training set -- which is the
1354 // same-geometry pinning this grouping exists to remove, so the length-
1355 // scale collapse it guards against survives it. Geometry g owns row
1356 // g + c * n_geom for stored channel ordinal c.
1357 Eigen::VectorXd geometry_id(n);
1358 for (Eigen::Index i = 0; i < n; ++i) {
1359 geometry_id(i) = static_cast<double>(n_geom > 0 ? i % n_geom : i);
1360 }
1361 const Eigen::VectorXd geometry_id_factor =
1362 permuted_factor_layout ? permuteTrainingVector(geometry_id)
1363 : geometry_id;
1364 std::vector<std::vector<Eigen::Index>> loo_groups;
1365 {
1366 std::unordered_map<long long, std::size_t> geom_to_group;
1367 for (Eigen::Index i = 0; i < geometry_id_factor.size(); ++i) {
1368 const long long gid =
1369 static_cast<long long>(std::llround(geometry_id_factor(i)));
1370 auto it = geom_to_group.find(gid);
1371 if (it == geom_to_group.end()) {
1372 geom_to_group.emplace(gid, loo_groups.size());
1373 loo_groups.emplace_back(1, i);
1374 } else {
1375 loo_groups[it->second].push_back(i);
1376 }
1377 }
1378 }
1379 // A geometry is one indivisible energy-and-gradient observation. Holding
1380 // out individual channels lets the retained channels at the same geometry
1381 // reveal the target and makes the score blind to length-scale collapse.
1382 const double loo_data =
1383 loo_basis.leaveOneOutNegativeLogPredictiveDensityGrouped(
1384 y_factor, total_sigma2, loo_groups);
1385 if (!std::isfinite(loo_data)) {
1386 fail();
1387 return;
1388 }
1389
1390 double eprior = 0.0;
1391 if (const_cov_fun) eprior -= const_cov_fun->calculateLogPrior();
1392 if (sexpat_cov_func) eprior -= sexpat_cov_func->calculateLogPrior();
1393 if (lik_gaussian) eprior -= lik_gaussian->evaluateLogPrior();
1394 energy_and_gradient.energy = loo_data + eprior;
1395
1396 energy_and_gradient.gradient.resize(w.size());
1397 energy_and_gradient.gradient.setZero();
1398
1399 Eigen::VectorXd uDdim;
1400 extractUniqueIndices(x_ind, uDdim);
1401
1402 for (Eigen::Index j = 0; j < w.size(); ++j) {
1403 Eigen::VectorXd direction = Eigen::VectorXd::Zero(w.size());
1404 direction(j) = 1.0;
1405 EigenMatrix dK;
1406 EigenMatrix d2K;
1408 geom, x, x_ind, uDdim, direction, dK, d2K,
1409 /*serial_per_rank=*/true)) {
1410 fail();
1411 return;
1412 }
1413 if (dK.rows() != n || dK.cols() != n || !dK.allFinite()) {
1414 fail();
1415 return;
1416 }
1417 if (permuted_factor_layout)
1419 dK = 0.5 * (dK + dK.transpose().eval());
1420
1421 const double derivative =
1422 loo_basis
1423 .leaveOneOutNegativeLogPredictiveDensityGroupedDirectionalDerivative(
1424 y_factor, total_sigma2, dK, loo_groups);
1425 if (!std::isfinite(derivative)) {
1426 fail();
1427 return;
1428 }
1429 energy_and_gradient.gradient(j) = derivative;
1430 }
1431
1432 if (sexpat_cov_func) {
1433 const FieldMatrixd gprior_cf =
1434 -sexpat_cov_func->calculateLogPriorGradient();
1435 const Eigen::Index n_prior = std::min<Eigen::Index>(
1436 gprior_cf.size(), energy_and_gradient.gradient.size());
1437 if (n_prior > 0) {
1438 energy_and_gradient.gradient.head(n_prior) +=
1439 Eigen::Map<const Eigen::VectorXd>(gprior_cf.data(), n_prior);
1440 }
1441 }
1442 if (theta_includes_likelihood_noise_ && lik_gaussian &&
1443 energy_and_gradient.gradient.size() > covarianceParameterCount()) {
1444 FieldMatrixd gprior_lik;
1445 lik_gaussian->evaluateLogPriorGradient(gprior_lik);
1446 if (gprior_lik.size() > 0) {
1447 energy_and_gradient.gradient(energy_and_gradient.gradient.size() -
1448 1) += -gprior_lik(0, 0);
1449 }
1450 }
1451 if (std::getenv("GPR_LOO_TRACE")) {
1452 static int loo_trace_count = 0;
1453 std::fprintf(stderr,
1454 "[loo-trace] eval=%d n=%lld theta=", loo_trace_count++,
1455 static_cast<long long>(n));
1456 for (Eigen::Index j = 0; j < w.size(); ++j)
1457 std::fprintf(stderr, " %.17g", w(j));
1458 std::fprintf(stderr,
1459 "\n[loo-trace] covnorm=%.17g covtrace=%.17g "
1460 "covsum=%.17g sigma2=%.17g rank=%d\n",
1461 noisy_cov.norm(), noisy_cov.trace(), noisy_cov.sum(),
1462 total_sigma2, loo_basis.rank());
1463 std::fprintf(stderr, "[loo-trace] S=");
1464 for (Eigen::Index j = 0; j < loo_basis.singularValues().size(); ++j)
1465 std::fprintf(stderr, " %.17g", loo_basis.singularValues()(j));
1466 std::fprintf(stderr,
1467 "\n[loo-trace] loo_data=%.17g eprior=%.17g "
1468 "energy=%.17g grad=",
1469 loo_data, eprior, energy_and_gradient.energy);
1470 for (Eigen::Index j = 0; j < energy_and_gradient.gradient.size(); ++j)
1471 std::fprintf(stderr, " %.17g", energy_and_gradient.gradient(j));
1472 std::fprintf(stderr, "\n");
1473 }
1474}

◆ evaluateLocalLooGeometryTerm()

double gpr::GaussianProcessRegression::evaluateLocalLooGeometryTerm ( const EigenMatrix & x,
const Eigen::VectorXd & x_ind,
const Eigen::VectorXd & y,
const gpr::FieldMatrixd & geom_dist,
Eigen::Index i,
Eigen::Index n_geom,
Eigen::Index n_blocks,
double total_sigma2,
Eigen::VectorXd * parameter_gradient = nullptr )
nodiscard

Definition at line 1700 of file EnergyGradient.cpp.

1705{
1706 const std::vector<Eigen::Index> neighbors =
1707 localLooNeighborIndices(geom_dist, i, n_geom);
1708 if (neighbors.empty()) return std::numeric_limits<double>::quiet_NaN();
1709
1710 const std::vector<Eigen::Index> rows_i =
1711 localLooGeometryBlockRows({i}, n_geom, n_blocks);
1712 const std::vector<Eigen::Index> rows_J =
1713 localLooGeometryBlockRows(neighbors, n_geom, n_blocks);
1714
1715 EigenMatrix x_i, x_J;
1716 Eigen::VectorXd x_ind_i, x_ind_J, y_i, y_J;
1717 localLooGatherRows(x, x_ind, y, rows_i, x_i, x_ind_i, y_i);
1718 localLooGatherRows(x, x_ind, y, rows_J, x_J, x_ind_J, y_J);
1719
1720 // K_JJ is the ordinary NOISY training covariance of the neighborhood
1721 // (evaluateTrainingCovarianceMatrix already adds lik_gaussian's sigma2
1722 // diagonal); jitter_sigma2 is layered on top to match the global LOO
1723 // path's total_sigma2 = getSigma2() + jitter_sigma2 convention.
1724 EigenMatrix K_JJ;
1725 evaluateTrainingCovarianceMatrix(x_J, x_ind_J, K_JJ,
1726 /*serial_per_rank=*/true);
1727 if (K_JJ.rows() != K_JJ.cols() || K_JJ.rows() != x_J.rows() ||
1728 !K_JJ.allFinite()) {
1729 return std::numeric_limits<double>::quiet_NaN();
1730 }
1731 if (jitter_sigma2 > 0.0) K_JJ.diagonal().array() += jitter_sigma2;
1732 // Marchildon-Zingg principled nugget (see Helpers.h): a data-driven
1733 // condition-floor for the dense LLT solve, the local-block analogue of
1734 // the HS-SVD path's conditionFlooredSigma2 (that helper floors the
1735 // singular values of a StableBasisND factorization, which this plain
1736 // dense block does not have). Small neighborhoods are exactly where
1737 // this matters: the degenerate-guard widening above can pull in two
1738 // near-duplicate geometries, and a handful of rows gives the LLT much
1739 // less slack against near-singularity than the full training kernel.
1740 if (!principled_nugget_)
1741 applyPrincipledDiagonalNugget(
1742 K_JJ, static_cast<Eigen::Index>(neighbors.size()), n_blocks - 1,
1744 /*gradient_enhanced=*/true);
1745
1746 const Eigen::LLT<EigenMatrix> llt(K_JJ);
1747 if (llt.info() != Eigen::Success) {
1748 return std::numeric_limits<double>::quiet_NaN();
1749 }
1750
1751 EigenMatrix K_iJ, K_ii;
1752 evaluateCovarianceMatrix(x_i, x_J, x_ind_i, x_ind_J, K_iJ,
1753 /*serial_per_rank=*/true);
1754 evaluateCovarianceMatrix(x_i, x_i, x_ind_i, x_ind_i, K_ii,
1755 /*serial_per_rank=*/true);
1756 if (K_iJ.rows() != y_i.size() || K_iJ.cols() != y_J.size() ||
1757 !K_iJ.allFinite() || !K_ii.allFinite()) {
1758 return std::numeric_limits<double>::quiet_NaN();
1759 }
1760
1761 // Standard GP posterior predictive of a NEW noisy observation at i
1762 // given the neighborhood J: mu = K_iJ (K_JJ)^-1 y_J,
1763 // Sigma = K_ii - K_iJ (K_JJ)^-1 K_Ji + total_sigma2 I (the "+ noise"
1764 // term matches predicting y, not the latent f, the same convention the
1765 // global LOO path uses for its C = K + sigma2 I).
1766 // One refinement step. On this neighbourhood the unrefined solve
1767 // misses Richardson by 2.64e-9 on component 1 and the retired
1768 // cbrt(eps) difference by 1.15e-6, past the 1e-6 check. The extra
1769 // triangular correction brings those errors to 1.95e-9 and 6.63e-7.
1770 auto refine_vector = [&](const Eigen::VectorXd& rhs) {
1771 Eigen::VectorXd solved = llt.solve(rhs);
1772 solved += llt.solve(rhs - K_JJ * solved);
1773 return solved;
1774 };
1775 auto refine_matrix = [&](const EigenMatrix& rhs) {
1776 EigenMatrix solved = llt.solve(rhs);
1777 solved += llt.solve(rhs - K_JJ * solved);
1778 return solved;
1779 };
1780 const Eigen::VectorXd alpha_J = refine_vector(y_J);
1781 const EigenMatrix W = refine_matrix(K_iJ.transpose());
1782 const Eigen::VectorXd mu_i = K_iJ * alpha_J;
1783 EigenMatrix Sigma_i = K_ii - K_iJ * W;
1784 Sigma_i.diagonal().array() += total_sigma2;
1785
1786 double nlp = 0.0;
1787 const double log_two_pi = numerics::log(2.0 * std::acos(-1.0));
1788 for (Eigen::Index r = 0; r < y_i.size(); ++r) {
1789 const double v = Sigma_i(r, r);
1790 if (!(v > 0.0) || !std::isfinite(v)) {
1791 return std::numeric_limits<double>::quiet_NaN();
1792 }
1793 const double resid = y_i(r) - mu_i(r);
1794 nlp += 0.5 * (log_two_pi + numerics::log(v) + resid * resid / v);
1795 }
1796 if (parameter_gradient == nullptr || parameter_gradient->size() == 0)
1797 return nlp;
1798
1799 // Neighbors stay at the current length scale. The radius cutoff is
1800 // piecewise smooth; off that kink the derivative is this contraction.
1801 // A directional block that does not assemble refuses with NaN rather
1802 // than a difference of the scalar above.
1803 Eigen::VectorXd term_gradient =
1804 Eigen::VectorXd::Zero(parameter_gradient->size());
1805 Eigen::VectorXd u_J;
1806 extractUniqueIndices(x_ind_J, u_J);
1807 const double eta =
1808 principled_nugget_
1809 ? 0.0
1810 : computePrincipledNugget(
1811 static_cast<Eigen::Index>(neighbors.size()), n_blocks - 1,
1812 principledKappaMaxDefault(), /*gradient_enhanced=*/true);
1813 const double diagonal_scale = 1.0 + eta;
1814 const Eigen::Index n_cov = covarianceParameterCount();
1815 for (Eigen::Index j = 0; j < term_gradient.size(); ++j) {
1816 Eigen::VectorXd direction = Eigen::VectorXd::Zero(term_gradient.size());
1817 direction(j) = 1.0;
1818 EigenMatrix dK_JJ, unused_second;
1819 assembleDirectionalCovarianceDerivatives(x_J, x_ind_J, u_J, direction,
1820 dK_JJ, unused_second,
1821 /*serial_per_rank=*/true);
1822 if (dK_JJ.rows() != K_JJ.rows() || dK_JJ.cols() != K_JJ.cols() ||
1823 !dK_JJ.allFinite()) {
1824 return std::numeric_limits<double>::quiet_NaN();
1825 }
1826 dK_JJ = 0.5 * (dK_JJ + dK_JJ.transpose().eval());
1827 if (diagonal_scale != 1.0) dK_JJ.diagonal().array() *= diagonal_scale;
1828
1829 EigenMatrix dK_iJ, dK_ii;
1830 if (!sexpatCrossDirectional(*this, x_i, x_ind_i, x_J, x_ind_J,
1831 direction, dK_iJ) ||
1832 dK_iJ.rows() != K_iJ.rows() || dK_iJ.cols() != K_iJ.cols() ||
1833 !sexpatCrossDirectional(*this, x_i, x_ind_i, x_i, x_ind_i,
1834 direction, dK_ii) ||
1835 dK_ii.rows() != K_ii.rows() || dK_ii.cols() != K_ii.cols()) {
1836 return std::numeric_limits<double>::quiet_NaN();
1837 }
1838 dK_ii = 0.5 * (dK_ii + dK_ii.transpose().eval());
1839
1840 const Eigen::VectorXd d_alpha = refine_vector(-(dK_JJ * alpha_J));
1841 const EigenMatrix dW = refine_matrix(dK_iJ.transpose() - dK_JJ * W);
1842 const Eigen::VectorXd d_mu = dK_iJ * alpha_J + K_iJ * d_alpha;
1843 const EigenMatrix d_sigma = dK_ii - dK_iJ * W - K_iJ * dW;
1844 if (!d_mu.allFinite() || !d_sigma.allFinite()) {
1845 return std::numeric_limits<double>::quiet_NaN();
1846 }
1847 const double d_noise =
1848 (theta_includes_likelihood_noise_ &&
1849 j + 1 == term_gradient.size() && term_gradient.size() > n_cov)
1851 : 0.0;
1852 double d_nlp = 0.0;
1853 for (Eigen::Index r = 0; r < y_i.size(); ++r) {
1854 const double v = Sigma_i(r, r);
1855 const double resid = y_i(r) - mu_i(r);
1856 const double dv = d_sigma(r, r) + d_noise;
1857 d_nlp += 0.5 * (1.0 - resid * resid / v) * (dv / v) -
1858 (resid / v) * d_mu(r);
1859 }
1860 if (!std::isfinite(d_nlp))
1861 return std::numeric_limits<double>::quiet_NaN();
1862 term_gradient(j) = d_nlp;
1863 }
1864 parameter_gradient->noalias() += term_gradient;
1865 return nlp;
1866}
double principledKappaMaxDefault()
Definition Helpers.h:244

◆ evaluateLocalNeighborhoodLooEnergy()

double gpr::GaussianProcessRegression::evaluateLocalNeighborhoodLooEnergy ( const Eigen::VectorXd & w,
const EigenMatrix & x,
const Eigen::VectorXd & x_ind,
const Eigen::VectorXd & y )
nodiscard

Definition at line 1868 of file EnergyGradient.cpp.

1871{
1872 return evaluateLocalNeighborhoodLooObjective(w, x, x_ind, y, nullptr);
1873}
double evaluateLocalNeighborhoodLooObjective(const Eigen::VectorXd &w, const EigenMatrix &x, const Eigen::VectorXd &x_ind, const Eigen::VectorXd &y, Eigen::VectorXd *gradient)

◆ evaluateLocalNeighborhoodLooEnergyAndGradientFromGeometry()

void gpr::GaussianProcessRegression::evaluateLocalNeighborhoodLooEnergyAndGradientFromGeometry ( const Eigen::VectorXd & w,
const TrainingKernelGeometry & geom,
const EigenMatrix & x,
const Eigen::VectorXd & x_ind,
const Eigen::VectorXd & y,
EnergyAndGradient & energy_and_gradient )

Definition at line 1984 of file EnergyGradient.cpp.

1989{
1990 if (detail::rejectInvalidHyperparameters(w, energy_and_gradient)) return;
1991 ++local_loo_objective_evaluations_for_testing_;
1992
1993 energy_and_gradient.gradient.resize(w.size());
1994 energy_and_gradient.gradient.setZero();
1996 w, x, x_ind, y, &energy_and_gradient.gradient);
1997 if (!std::isfinite(energy_and_gradient.energy)) {
1998 energy_and_gradient.gradient.setZero();
1999 setParameters(w);
2000 return;
2001 }
2002 // The objective's setParameters(w) is the point the returned energy
2003 // and gradient are at. Repeat it so a later read cannot observe a
2004 // directional assembly's temporary kernel state.
2005 setParameters(w);
2006}

◆ evaluateLocalNeighborhoodLooGeometryTermForTesting()

double gpr::GaussianProcessRegression::evaluateLocalNeighborhoodLooGeometryTermForTesting ( const Eigen::VectorXd & w,
const EigenMatrix & x,
const Eigen::VectorXd & x_ind,
const Eigen::VectorXd & y,
Eigen::Index geometry_index )
nodiscard

Definition at line 1658 of file EnergyGradient.cpp.

1662{
1663 if (!detail::logParametersAreRepresentable(w)) {
1664 return std::numeric_limits<double>::infinity();
1665 }
1666 setParameters(w);
1667 if (sexpat_cov_func == nullptr || lik_gaussian == nullptr ||
1668 x.rows() == 0 || x_ind.size() != x.rows() || y.size() != x.rows()) {
1669 return std::numeric_limits<double>::quiet_NaN();
1670 }
1671 const detail::ObservationChannelLayout channels(x_ind);
1672 const Eigen::Index n_blocks = channels.channelCount();
1673 const Eigen::Index n_geom = channels.rowsPerChannel();
1674 const auto& configuration = sexpat_cov_func->getConfInfo();
1675 Coord R_geom;
1676 if (!extractGroupedGeometryPositions(x, channels, configuration, R_geom)) {
1677 return std::numeric_limits<double>::quiet_NaN();
1678 }
1679 if (n_geom < 2 || geometry_index < 0 || geometry_index >= n_geom) {
1680 return std::numeric_limits<double>::quiet_NaN();
1681 }
1682
1683 const gpr::FieldMatrixd& ls_ref = sexpat_cov_func->getLengthScaleRef();
1684 if (ls_ref.size() == 0) return std::numeric_limits<double>::quiet_NaN();
1685
1686 aux::Distance kernel_distance;
1687 gpr::FieldMatrixd geom_dist;
1688 kernel_distance.dist_at(R_geom, R_geom, configuration, ls_ref, geom_dist);
1689 if (geom_dist.rows() != n_geom || geom_dist.cols() != n_geom) {
1690 return std::numeric_limits<double>::quiet_NaN();
1691 }
1692
1693 const double total_sigma2 = lik_gaussian->getSigma2() + jitter_sigma2;
1694 if (!(total_sigma2 > 0.0)) return std::numeric_limits<double>::quiet_NaN();
1695
1696 return evaluateLocalLooGeometryTerm(x, x_ind, y, geom_dist, geometry_index,
1697 n_geom, n_blocks, total_sigma2);
1698}
void dist_at(const gpr::Coord &x1, const gpr::Coord &x2, const gpr::AtomsConfiguration &conf_info, const gpr::FieldMatrixd &lengthscale, gpr::FieldMatrixd &dist, bool take_sqrt=true)
Give the distance between two atomic configurations as defined in the special GPstuff covariance func...
Definition Distance.cpp:620
double evaluateLocalLooGeometryTerm(const EigenMatrix &x, const Eigen::VectorXd &x_ind, const Eigen::VectorXd &y, const gpr::FieldMatrixd &geom_dist, Eigen::Index i, Eigen::Index n_geom, Eigen::Index n_blocks, double total_sigma2, Eigen::VectorXd *parameter_gradient=nullptr)

◆ evaluateLocalNeighborhoodLooObjective()

double gpr::GaussianProcessRegression::evaluateLocalNeighborhoodLooObjective ( const Eigen::VectorXd & w,
const EigenMatrix & x,
const Eigen::VectorXd & x_ind,
const Eigen::VectorXd & y,
Eigen::VectorXd * gradient )
nodiscard

Definition at line 1875 of file EnergyGradient.cpp.

1879{
1880 if (!detail::logParametersAreRepresentable(w)) {
1881 return std::numeric_limits<double>::infinity();
1882 }
1883 setParameters(w);
1884 if (sexpat_cov_func == nullptr || lik_gaussian == nullptr ||
1885 x.rows() == 0 || x_ind.size() != x.rows() || y.size() != x.rows()) {
1886 return std::numeric_limits<double>::quiet_NaN();
1887 }
1888
1889 // Directional consumers reuse the training permutation, so the objective
1890 // refreshes its factor layout for the supplied observation rows.
1892
1893 const detail::ObservationChannelLayout channels(x_ind);
1894 const Eigen::Index n_blocks = channels.channelCount();
1895 const Eigen::Index n_geom = channels.rowsPerChannel();
1896 const auto& configuration = sexpat_cov_func->getConfInfo();
1897 Coord R_geom;
1898 if (!extractGroupedGeometryPositions(x, channels, configuration, R_geom)) {
1899 return std::numeric_limits<double>::quiet_NaN();
1900 }
1901 if (n_geom < 2) return std::numeric_limits<double>::quiet_NaN();
1902
1903 const gpr::FieldMatrixd& ls_ref = sexpat_cov_func->getLengthScaleRef();
1904 if (ls_ref.size() == 0) return std::numeric_limits<double>::quiet_NaN();
1905
1906 aux::Distance kernel_distance;
1907 gpr::FieldMatrixd geom_dist;
1908 kernel_distance.dist_at(R_geom, R_geom, configuration, ls_ref, geom_dist);
1909 if (geom_dist.rows() != n_geom || geom_dist.cols() != n_geom) {
1910 return std::numeric_limits<double>::quiet_NaN();
1911 }
1912
1913 const double total_sigma2 = lik_gaussian->getSigma2() + jitter_sigma2;
1914 if (!(total_sigma2 > 0.0)) return std::numeric_limits<double>::quiet_NaN();
1915
1916 int rank = 0;
1917 int nprocs = 1;
1918#ifdef GPR_LINALG_SCALAPACK
1919 {
1920 auto& st = backend().distributed();
1921 st.initialize();
1922 rank = st.myrank();
1923 nprocs = st.nprocs();
1924 }
1925#endif
1926
1927 // Rank r owns geometries with i % nprocs == r. Each term is a
1928 // deterministic double, so an exact accumulator merged by integer
1929 // addition gives the same objective for every rank count.
1930 linalg::ExactSum objective;
1931 std::vector<linalg::ExactSum> grad_sums;
1932 if (gradient != nullptr) grad_sums.resize(gradient->size());
1933 for (Eigen::Index i = 0; i < n_geom; ++i) {
1934 if (static_cast<int>(i % nprocs) != rank) continue;
1935 if (gradient == nullptr) {
1936 objective.add(evaluateLocalLooGeometryTerm(
1937 x, x_ind, y, geom_dist, i, n_geom, n_blocks, total_sigma2));
1938 continue;
1939 }
1940 Eigen::VectorXd term_gradient = Eigen::VectorXd::Zero(gradient->size());
1941 objective.add(evaluateLocalLooGeometryTerm(
1942 x, x_ind, y, geom_dist, i, n_geom, n_blocks, total_sigma2,
1943 &term_gradient));
1944 for (Eigen::Index j = 0; j < term_gradient.size(); ++j)
1945 grad_sums[static_cast<std::size_t>(j)].add(term_gradient(j));
1946 }
1947
1948#ifdef GPR_LINALG_SCALAPACK
1949 if (nprocs > 1) {
1950 backend().exact_sum_bcast(&objective, 1);
1951 for (auto& component: grad_sums)
1952 backend().exact_sum_bcast(&component, 1);
1953 }
1954#endif
1955
1956 double eprior = 0.0;
1957 if (const_cov_fun) eprior -= const_cov_fun->calculateLogPrior();
1958 if (sexpat_cov_func) eprior -= sexpat_cov_func->calculateLogPrior();
1959 if (lik_gaussian) eprior -= lik_gaussian->evaluateLogPrior();
1960 if (gradient != nullptr) {
1961 for (Eigen::Index j = 0; j < gradient->size(); ++j)
1962 (*gradient)(j) = grad_sums[static_cast<std::size_t>(j)].value();
1963 if (sexpat_cov_func) {
1964 const FieldMatrixd gprior_cf =
1965 -sexpat_cov_func->calculateLogPriorGradient();
1966 const Eigen::Index n_prior =
1967 std::min<Eigen::Index>(gprior_cf.size(), gradient->size());
1968 if (n_prior > 0) {
1969 gradient->head(n_prior) += Eigen::Map<const Eigen::VectorXd>(
1970 gprior_cf.data(), n_prior);
1971 }
1972 }
1973 if (theta_includes_likelihood_noise_ && lik_gaussian &&
1974 gradient->size() > covarianceParameterCount()) {
1975 FieldMatrixd gprior_lik;
1976 lik_gaussian->evaluateLogPriorGradient(gprior_lik);
1977 if (gprior_lik.size() > 0)
1978 (*gradient)(gradient->size() - 1) += -gprior_lik(0, 0);
1979 }
1980 }
1981 return objective.value() + eprior;
1982}

◆ evaluateNlmlHessianVector()

bool gpr::GaussianProcessRegression::evaluateNlmlHessianVector ( const Eigen::VectorXd & x_ind,
const EigenMatrix & x,
const Eigen::VectorXd & y,
const Eigen::VectorXd & direction,
Eigen::VectorXd & product,
const TrainingKernelGeometry * training_geom = nullptr )

Exact Hessian-vector product of the negative log marginal likelihood, including the covariance-function prior.

H v = d/deps grad NLML(theta + eps v) at eps = 0. The data term is contracted from the cached inverse, alpha = K^{-1} y, and the kernel derivatives already used by the analytic gradient. beta = K^{-1}(D alpha) is the only new triangular solve. The MAP penalty is not included.

Returns false when exactNlmlHessianVectorAvailable() is false, for a missing factor, an HS-SVD Q-form objective, or a failed derivative assembly. The nlml_hessian_vector curvature mode then takes the finite_difference path, logged and counted.

Definition at line 371 of file Hessian.cpp.

375{
376 const auto curvature_start = std::chrono::steady_clock::now();
377 const double solve0 = linalg::teamSolveWallSeconds();
378 const double factor0 = linalg::teamFactorWallSeconds();
379 const double eigen0 = PhaseTimers::eigensolve_seconds;
380 const double kernel0 = PhaseTimers::assembly_seconds;
381 struct ExclusiveCurvature {
382 std::chrono::steady_clock::time_point start;
383 double solve0, factor0, eigen0, kernel0;
384 ~ExclusiveCurvature()
385 {
386 const double wall = std::chrono::duration<double>(
387 std::chrono::steady_clock::now() - start)
388 .count();
389 const double nested = (linalg::teamSolveWallSeconds() - solve0) +
390 (linalg::teamFactorWallSeconds() - factor0) +
391 (PhaseTimers::eigensolve_seconds - eigen0) +
392 (PhaseTimers::assembly_seconds - kernel0);
393 PhaseTimers::curvature_seconds += std::max(0.0, wall - nested);
394 }
395 } exclusive{curvature_start, solve0, factor0, eigen0, kernel0};
396
398 fail_nlml_hessian_vector_for_testing_) {
399 return false;
400 }
401 if (!is_decomposed_succesfully || sexpat_cov_func == nullptr ||
402 direction.size() == 0 || !direction.allFinite() || y.size() == 0) {
403 return false;
404 }
405 // The Q-form Woodbury inverse is not the Cholesky factor. Applying the
406 // factor to that objective would be a different operator.
407 if (use_hssvd_backend_ && use_hssvd_objective_contractions_ &&
408 hssvdObjectiveStampMatches() && !hssvd_objective_trace_via_cholesky_) {
409 return false;
410 }
411 if (!hasTrainingCholeskyFactor(y.rows())) return false;
412#ifdef GPR_LINALG_KOKKOS
413 if (!hasDevicePosterior() && b.rows() != activeFactorOrder(y.rows()))
414 return false;
415#else
416 if (b.rows() != activeFactorOrder(y.rows())) return false;
417#endif
418
419 Eigen::VectorXd alpha;
420#ifdef GPR_LINALG_KOKKOS
421 if (hasDevicePosterior()) {
423 alpha = a;
424 } else
425#endif
426 alpha = trainingSolver().unwhiten(b);
427 const EigenMatrix inverse = trainingSolver().inverse();
428 // As in evaluateDirectionalCurvature: contract the projected derivatives
429 // against the deflated factor and add the noise-only rigid block in
430 // closed form.
431 const bool deflated = rigid_deflation_.isActiveForFullOrder(y.rows());
432 const Eigen::Index order = activeFactorOrder(y.rows());
433 if (deflated && rigid_deflation_.a_rigid.size() != y.rows()) {
434 rigid_deflation_.updateTargetStats(
436 }
437 if (alpha.size() != order || !alpha.allFinite() ||
438 inverse.rows() != order || inverse.cols() != order ||
439 !inverse.allFinite()) {
440 return false;
441 }
442
443 const Eigen::Index p = direction.size();
444 const bool permute = hasTrainingPermutation();
445 const auto factor_frame = [&](EigenMatrix& matrix) {
446 if (permute) {
448 }
449 if (deflated) matrix = rigid_deflation_.projectSymmetric(matrix);
450 };
451
452 // beta = K^{-1} (D alpha) is the one triangular pair. The inverse above
453 // is the factor's cached inverse (the analytic gradient already formed
454 // it); forming it on a cold cache is that same inverse, not a solve
455 // per column.
456 Eigen::VectorXd data(p);
457 auto contract = [&](auto&& assemble) -> bool {
458 EigenMatrix directional;
459 EigenMatrix second_direction;
460 if (!assemble(direction, directional, second_direction)) return false;
461 factor_frame(directional);
462 const Eigen::VectorXd beta =
463 trainingSolver().solve(directional * alpha);
464 if (beta.size() != alpha.size() || !beta.allFinite()) return false;
465 const EigenMatrix metric = (inverse * directional) * inverse;
466 const auto [noise_first, noise_second] =
467 rigidNoiseDerivatives(direction);
468 for (Eigen::Index i = 0; i < p; ++i) {
469 const Eigen::VectorXd axis = Eigen::VectorXd::Unit(p, i);
470 EigenMatrix kernel_i;
471 EigenMatrix second_i;
472 EigenMatrix unused;
473 EigenMatrix second_sum;
474 if (!assemble(axis, kernel_i, second_i) ||
475 !assemble(direction + axis, unused, second_sum)) {
476 return false;
477 }
478 EigenMatrix mixed =
479 0.5 * (second_sum - second_direction - second_i);
480 factor_frame(kernel_i);
481 factor_frame(mixed);
482 data(i) = detail::nlmlHessianVectorComponent(
483 inverse, alpha, beta, metric, kernel_i, mixed);
484 if (deflated) {
485 const auto [axis_first, axis_second] =
487 const double sum_second =
488 rigidNoiseDerivatives(direction + axis).second;
489 data(i) += rigid_deflation_.rigidCurvature(
490 noise_first, axis_first,
491 0.5 * (sum_second - noise_second - axis_second));
492 }
493 }
494 return data.allFinite();
495 };
496
497 bool contracted = false;
498 if (sexpat_cov_func->usesManifoldChart()) {
499 std::vector<EigenMatrix> kernel_derivatives;
501 x, x_ind, *sexpat_cov_func, kernel_derivatives) ||
502 kernel_derivatives.empty() ||
503 static_cast<Eigen::Index>(kernel_derivatives.size()) !=
505 kernel_derivatives.front().rows() != y.rows()) {
506 return false;
507 }
508 const auto assemble_chart = [&](const Eigen::VectorXd& dir,
509 EigenMatrix& first,
510 EigenMatrix& second) -> bool {
512 x, x_ind, *sexpat_cov_func, dir, second)) {
513 return false;
514 }
515 return second.rows() == y.rows() &&
516 composeChartDirection(kernel_derivatives,
519 lik_gaussian != nullptr &&
520 lik_gaussian->getOptimizeSigma2(),
521 dir, first, second) &&
522 first.rows() == y.rows();
523 };
524 contracted = contract(assemble_chart);
525 } else {
526 Eigen::VectorXd uDdim;
527 extractUniqueIndices(x_ind, uDdim);
528 TrainingKernelGeometry local_geom;
529 if (training_geom == nullptr) {
530 if (use_pair_local_directional_tiles_ && use_pair_local_tiles_)
531 training_geom = fitGeometryFor(x, x_ind);
532 else if (prepareTrainingKernelGeometry(x, x_ind, local_geom))
533 training_geom = &local_geom;
534 }
535 const auto assemble_pair = [&](const Eigen::VectorXd& dir,
536 EigenMatrix& first,
537 EigenMatrix& second) -> bool {
538 bool ready = false;
539 if (training_geom != nullptr) {
541 *training_geom, x, x_ind, uDdim, dir, first, second,
542 /*serial_per_rank=*/false);
543 }
544 if (!ready) {
546 x, x_ind, uDdim, dir, first, second,
547 /*serial_per_rank=*/false);
548 }
549 return first.rows() == y.rows() && first.cols() == y.rows() &&
550 second.rows() == y.rows() && second.cols() == y.rows() &&
551 first.allFinite() && second.allFinite();
552 };
553 contracted = contract(assemble_pair);
554 }
555 if (!contracted) return false;
556
557 for (Eigen::Index i = 0; i < p; ++i) {
558 const Eigen::VectorXd axis = Eigen::VectorXd::Unit(p, i);
559 data(i) -=
560 sexpat_cov_func->calculateDirectionalLogPriorCurvature(axis) *
561 direction(i);
562 }
563 if (!data.allFinite()) return false;
564 product = std::move(data);
565 return true;
566}
virtual bool exactNlmlHessianVectorAvailable() const noexcept
Eigen::VectorXd assemble(const DeviceEnvironments &left_environments, const DeviceEnvironments &right_environments, const gpr::detail::EnvironmentPairBatch &batch, std::size_t scratch_bytes)

◆ evaluatePriorMeanTargets()

void gpr::GaussianProcessRegression::evaluatePriorMeanTargets ( const Eigen::VectorXd & positions,
double & energy,
Eigen::VectorXd & gradient ) const

Prior-mean targets for a virtual (conditioning-only) observation at ~positions~.

Fills the energy and gradient of the configured prior mean at the query geometry (zeros when no prior mean is active), so a virtual observation built from them carries an exactly-zero residual under the model's prior-mean subtraction.

Definition at line 1049 of file GaussianProcessRegression.cpp.

1052{
1053 energy = 0.0;
1054 gradient = Eigen::VectorXd::Zero(positions.size());
1055 if (secant_quadratic_prior_active_) {
1056 if (positions.size() != secant_reference_position_.size() ||
1057 !positions.allFinite())
1058 throw std::logic_error(
1059 "secant quadratic mean requires a matching query");
1060 const Eigen::VectorXd displacement =
1061 positions - secant_reference_position_;
1062 gradient = secant_reference_gradient_ + secant_hessian_ * displacement;
1063 energy = secant_reference_energy_ +
1064 secant_reference_gradient_.dot(displacement) +
1065 0.5 * displacement.dot(secant_hessian_ * displacement);
1066 if (!std::isfinite(energy) || !gradient.allFinite())
1067 throw std::runtime_error(
1068 "secant quadratic mean produced a non-finite target");
1069 ++secant_quadratic_prior_uses_;
1070 if (ffPriorMeanActive()) {
1071 const auto evaluation =
1072 ff_prior_mean_->evaluate(positions.transpose());
1073 energy += evaluation.energy;
1074 gradient += evaluation.gradient.transpose();
1075 return;
1076 }
1077 if (!zblPriorMeanActive()) return;
1078 const auto evaluation =
1079 zbl_prior_mean_->evaluate(positions.transpose());
1080 energy += evaluation.energy;
1081 gradient += evaluation.gradient.transpose();
1082 return;
1083 }
1084 if (ffPriorMeanActive()) {
1085 const auto evaluation = ff_prior_mean_->evaluate(positions.transpose());
1086 energy = evaluation.energy;
1087 gradient = evaluation.gradient.transpose();
1088 return;
1089 }
1090 if (!zblPriorMeanActive()) return;
1091 const auto evaluation = zbl_prior_mean_->evaluate(positions.transpose());
1092 energy = evaluation.energy;
1093 gradient = evaluation.gradient.transpose();
1094}

◆ evaluateTrainingCovarianceInFactorOrder()

bool gpr::GaussianProcessRegression::evaluateTrainingCovarianceInFactorOrder ( const EigenMatrix & x,
const Eigen::VectorXd & x_ind,
EigenMatrix & cov_matrix,
bool include_noise = true )
nodiscard

Noisy training covariance, constant excluded, written directly in the factor's observation-tiled order: each pair-local tile entry and each diagonal term lands where permuteSymmetricMatrix would move it, with the same values. False when the rows have no pair-local geometry or no tiled permutation; cov_matrix is then unspecified.

Definition at line 2340 of file CovarianceAssembly.cpp.

2343{
2344#ifdef GPR_LINALG_SCALAPACK
2345 (void)x;
2346 (void)x_ind;
2347 (void)cov_matrix;
2348 (void)include_noise;
2349 return false;
2350#else
2351 if (!hasTrainingPermutation() || sexpat_cov_func == nullptr ||
2352 lik_gaussian == nullptr)
2353 return false;
2354 TrainingKernelGeometry local_geometry;
2355 const TrainingKernelGeometry* geom = nullptr;
2356 {
2357 ScopedPhaseTimer preparation_timer(PhaseTimers::assembly_seconds);
2358 geom = fitGeometryFor(x, x_ind);
2359 if (geom == nullptr &&
2360 prepareTrainingKernelGeometry(x, x_ind, local_geometry))
2361 geom = &local_geometry;
2362 }
2363 return geom != nullptr &&
2365 *geom, x, x_ind, cov_matrix, include_noise);
2366#endif
2367}

◆ evaluateTrainingCovarianceInFactorOrderFromGeometry()

bool gpr::GaussianProcessRegression::evaluateTrainingCovarianceInFactorOrderFromGeometry ( const TrainingKernelGeometry & geom,
const EigenMatrix & x,
const Eigen::VectorXd & x_ind,
EigenMatrix & cov_matrix,
bool include_noise = true )
nodiscard

Definition at line 2369 of file CovarianceAssembly.cpp.

2374{
2375#ifdef GPR_LINALG_SCALAPACK
2376 (void)geom;
2377 (void)x;
2378 (void)x_ind;
2379 (void)cov_matrix;
2380 (void)include_noise;
2381 return false;
2382#else
2383 const Index_t n = static_cast<Index_t>(x.rows());
2384 if (!hasTrainingPermutation() || sexpat_cov_func == nullptr ||
2385 lik_gaussian == nullptr || n <= 0 ||
2386 x.rows() > std::numeric_limits<int>::max() || x_ind.size() != n ||
2387 !x_ind.allFinite() ||
2388 training_permutation_.inv_perm.size() != static_cast<std::size_t>(n) ||
2389 !geom.valid || geom.n != n ||
2390 std::any_of(geom.blocks.begin(), geom.blocks.end(),
2391 [&](const auto& block) {
2392 return !trainingBlockGeometryUsable(geom, block);
2393 }))
2394 return false;
2395 ScopedPhaseTimer assembly_timer(PhaseTimers::assembly_seconds);
2396 const auto& placement = training_permutation_.inv_perm;
2397 EigenMatrix Ktemp;
2398 if (!assembleSexpatCovFromGeometry(
2399 *this, backend(), geom, *sexpat_cov_func, x_ind, Ktemp,
2400 /*do_reduce=*/true, /*serial_per_rank=*/false, nullptr, nullptr,
2401 nullptr, nullptr, nullptr, nullptr, &placement))
2402 return false;
2403 // The same sequence as the channel-major assembly with the constant
2404 // excluded, each diagonal entry moved to its factor position.
2405 cov_matrix.resize(n, n);
2406 cov_matrix.setZero();
2407 cov_matrix.noalias() += Ktemp;
2408 Ktemp.resize(0, 0);
2409 applyKernelNugget(cov_matrix, n);
2410 if (const_cov_fun != nullptr) {
2411 const double eta = kernelNuggetCoefficient(n);
2412 if (eta != 0.0) {
2413 const Eigen::Index count =
2414 detail::leadingDerivativeBlockSize(x_ind, 0.0);
2415 for (Eigen::Index row = 0; row < count; ++row) {
2416 const auto at = placement[static_cast<std::size_t>(row)];
2417 cov_matrix(at, at) += eta * const_cov_fun->getConstSigma2();
2418 }
2419 }
2420 }
2421 if (include_noise) {
2422 const Eigen::VectorXd noise = lik_gaussian->evaluateTrainingVariance(x);
2423 for (Eigen::Index row = 0; row < n; ++row) {
2424 const auto at = placement[static_cast<std::size_t>(row)];
2425 cov_matrix(at, at) += noise(row);
2426 }
2427 }
2429 ++training_geometry_apply_calls_for_testing_;
2430 ++factor_order_assemblies_for_testing_;
2431 return true;
2432#endif
2433}
Eigen::Vector3d at(const FieldMatrixd &mat, Index_t i)

◆ evaluateTrainingCovarianceMatrix()

void gpr::GaussianProcessRegression::evaluateTrainingCovarianceMatrix ( const EigenMatrix & x,
const Eigen::VectorXd & x_ind,
EigenMatrix & cov_matrix,
bool serial_per_rank = false,
bool include_constant = true,
bool include_noise = true )

Evaluate training covariance matrix (gp_cov + noise covariance).

The function takes in matrix x that contains training input vectors to GPR. Returns the noisy covariance matrix cov_matrix for observations y, which is sum of noisless covariance matrix and diagonal term, for example, from Gaussian noise.

Every element ij of noisless covariance matrix contains covariance between inputs i and j in x. The noisless covariance matrix is formed with all covariance functions.

This is essentially the application of the kernel function to the training points

Parameters
xTraining input vectors to GP
x_indPer-row observation type or derivative-channel indices
cov_matrixNoisy covariance matrix for observations y
serial_per_rankAssemble a complete local matrix without a collective reduction
include_constantInclude the constant covariance component
include_noiseAdd observation noise to the diagonal

Definition at line 1875 of file CovarianceAssembly.cpp.

1878{
1879 Index_t n = (Index_t)x.rows();
1880 Eigen::VectorXd uDdim; // unique derivatives' dimensions
1881 EigenMatrix Ktemp;
1882
1883 // The per-block assembly below walks every (block_n, block_m) pair and
1884 // recomputes dist_at plus its exp() for each one, over coordinates that
1885 // assembleMatrixOfRepetitiveCoordinates replicated IDENTICALLY across
1886 // all D+1 blocks -- only the appended dimension tag differs. The
1887 // geometry route builds that shared content once and applies it
1888 // elementwise per block, which is the same saving the hyperparameter
1889 // sweep already takes through INLA and the gradient path. Leaving the
1890 // rematerialize on the per-block route cost roughly a second of wall
1891 // per training row on the Baker board, which is where the surrogate
1892 // spent the time it saved on true forces.
1893 TrainingKernelGeometry shared_geometry;
1894 const TrainingKernelGeometry* shared = nullptr;
1895 if (sexpat_cov_func != nullptr) {
1896 ScopedPhaseTimer preparation_timer(PhaseTimers::assembly_seconds);
1897 // The cached blocks serve every later evaluation at this design,
1898 // including the gradient at the same theta.
1899 shared = fitGeometryFor(x, x_ind);
1900 if (shared == nullptr &&
1901 prepareTrainingKernelGeometry(x, x_ind, shared_geometry)) {
1902 shared = &shared_geometry;
1903 }
1904 }
1905 if (shared != nullptr && evaluateTrainingCovarianceMatrixFromGeometry(
1906 *shared, x, x_ind, cov_matrix, serial_per_rank,
1907 include_constant, include_noise)) {
1908 return;
1909 }
1910 ScopedPhaseTimer assembly_timer(PhaseTimers::assembly_seconds);
1911 if (std::getenv("GPR_GEOM_DEBUG"))
1912 std::fprintf(stderr, "[geom] legacy assembly n=%lld\n",
1913 static_cast<long long>(n));
1914
1915 cov_matrix.resize(n, n);
1916 cov_matrix.setZero();
1917
1918 extractUniqueIndices(x_ind, uDdim);
1919
1920#ifdef GPR_LINALG_SCALAPACK
1921 if (serial_per_rank) {
1922 // Local path required by callers that hold rank-divergent kernel
1923 // state (e.g. SVGD per-particle predict, evaluateEnergyAnd-
1924 // GradientLocal): every rank assembles the full kernel without
1925 // touching MPI / BLACS. applyCovarianceFunction with
1926 // serial_per_rank=true skips both the round-robin block
1927 // distribution and the Allreduce. The LikGaussian noise diagonal
1928 // is rank-local already.
1929 addConstantCovarianceBlock(
1930 include_constant ? const_cov_fun.get() : nullptr, x_ind, x_ind,
1931 cov_matrix);
1932 applyCovarianceFunction(x, x_ind, uDdim, *sexpat_cov_func, Ktemp,
1933 /*do_reduce=*/false, /*serial_per_rank=*/true);
1934 cov_matrix.noalias() += Ktemp;
1935 applyKernelNugget(cov_matrix, n);
1936 if (!include_constant)
1937 detail::addSeparatedConstantNugget(const_cov_fun.get(), x_ind,
1938 kernelNuggetCoefficient(n),
1939 cov_matrix);
1940 if (include_noise)
1941 cov_matrix.diagonal() += lik_gaussian->evaluateTrainingVariance(x);
1942 } else {
1943 // Public dense assembly contract: every rank receives the same
1944 // covariance matrix. The direct Cholesky path uses
1945 // decomposeCovarianceMatrixScalapack and bypasses this dense API.
1946 auto& _st = backend().distributed();
1947 const int tile_size =
1948 static_cast<int>(detail::storedObservationChannelCount(x_ind));
1949 _st.initialize(tile_size);
1950 const auto ownership = applyCovarianceFunction(
1951 x, x_ind, uDdim, *sexpat_cov_func, Ktemp, false /* no reduce */);
1952
1953 // Reduce the one-owner-per-block sexpat partials BEFORE the
1954 // constant block and noise diagonal: every Ktemp entry then has
1955 // exactly one contributor, so the disjoint Allreduce is exact
1956 // and the subsequent rank-local const + lik adds reproduce the
1957 // single-rank assembly order (const, sexpat, lik) bit-for-bit
1958 // at every rank count.
1959 if (_st.nprocs() > 1 &&
1960 ownership == CovarianceAssemblyOwnership::Disjoint) {
1961 backend().disjoint_sum_bcast(Ktemp.data(),
1962 static_cast<int>(Ktemp.size()));
1963 ++distributed_training_covariance_assemblies_for_testing_;
1964 }
1965 addConstantCovarianceBlock(
1966 include_constant ? const_cov_fun.get() : nullptr, x_ind, x_ind,
1967 cov_matrix);
1968 cov_matrix.noalias() += Ktemp;
1969 applyKernelNugget(cov_matrix, n);
1970 if (!include_constant)
1971 detail::addSeparatedConstantNugget(const_cov_fun.get(), x_ind,
1972 kernelNuggetCoefficient(n),
1973 cov_matrix);
1974 if (include_noise)
1975 cov_matrix.diagonal() += lik_gaussian->evaluateTrainingVariance(x);
1976 }
1977#else
1978 (void)serial_per_rank;
1979 // Non-MPI path: sequential dense assembly.
1980 addConstantCovarianceBlock(include_constant ? const_cov_fun.get() : nullptr,
1981 x_ind, x_ind, cov_matrix);
1982
1983 applyCovarianceFunction(x, x_ind, uDdim, *sexpat_cov_func, Ktemp);
1984 cov_matrix.noalias() += Ktemp;
1985 applyKernelNugget(cov_matrix, n);
1986 if (!include_constant)
1987 detail::addSeparatedConstantNugget(
1988 const_cov_fun.get(), x_ind, kernelNuggetCoefficient(n), cov_matrix);
1989
1990#ifndef NDEBUG
1991 gpr::assertMsg(lik_gaussian != nullptr,
1992 "Object of Gausian likelihood is not allocated!");
1993#endif
1994 if (include_noise)
1995 cov_matrix.diagonal() += lik_gaussian->evaluateTrainingVariance(x);
1996#endif
1997
1998 // log_man << "Training covariance matrix is " << cov_matrix.size() << "
1999 // over ( " << cov_matrix.rows() << ", " << cov_matrix.cols() << " )" <<
2000 // "\n";
2002}

◆ evaluateTrainingCovarianceMatrixFromGeometry()

bool gpr::GaussianProcessRegression::evaluateTrainingCovarianceMatrixFromGeometry ( const TrainingKernelGeometry & geom,
const EigenMatrix & x,
const Eigen::VectorXd & x_ind,
EigenMatrix & cov_matrix,
bool serial_per_rank = false,
bool include_constant = true,
bool include_noise = true )
nodiscard

Definition at line 2209 of file CovarianceAssembly.cpp.

2213{
2214 ScopedPhaseTimer assembly_timer(PhaseTimers::assembly_seconds);
2215 const auto asm_t0 = std::chrono::steady_clock::now();
2216 struct AsmReport {
2217 const std::chrono::steady_clock::time_point& t0;
2218 Eigen::Index rows;
2219 std::size_t blocks;
2220 ~AsmReport()
2221 {
2222 if (std::getenv("GPR_GEOM_DEBUG")) {
2223 const double ms = std::chrono::duration<double, std::milli>(
2224 std::chrono::steady_clock::now() - t0)
2225 .count();
2226 std::fprintf(
2227 stderr,
2228 "[geom] apply n=%lld blocks=%zu ms=%.1f rss_mb=%.0f\n",
2229 static_cast<long long>(rows), blocks, ms,
2230 PhaseTimers::residentMegabytes());
2231 }
2232 }
2233 } asm_report{asm_t0, x.rows(), geom.blocks.size()};
2234 double invalid_geometry =
2235 !geom.valid || geom.n != x.rows() || x.rows() <= 0 ||
2236 x.rows() > std::numeric_limits<int>::max() ||
2237 x_ind.size() != x.rows() || !x_ind.allFinite() ||
2238 sexpat_cov_func == nullptr || lik_gaussian == nullptr ||
2239 std::any_of(geom.blocks.begin(), geom.blocks.end(),
2240 [&](const auto& block) {
2241 return !trainingBlockGeometryUsable(geom, block);
2242 });
2243 // All participants reject invalid geometry before any rank enters the
2244 // matrix reduction. Rank-local queries leave the factor's grid intact.
2245 if (!serial_per_rank)
2246 linalg::ordered_sum_bcast(&invalid_geometry, 1, backend().mpi());
2247 if (invalid_geometry != 0.0) {
2248 if (std::getenv("GPR_GEOM_DEBUG"))
2249 std::fprintf(stderr, "[geom] fallback at apply line %d\n",
2250 __LINE__);
2251 return false;
2252 }
2253 const Index_t n = static_cast<Index_t>(x.rows());
2254 if (std::getenv("GPR_GEOM_DEBUG"))
2255 std::fprintf(stderr, "[geom] apply entry rss_mb=%.0f\n",
2257 cov_matrix.resize(n, n);
2258 cov_matrix.setZero();
2259
2260 EigenMatrix Ktemp;
2261#ifdef GPR_LINALG_SCALAPACK
2262 auto& _st = backend().distributed();
2263 // serial_per_rank callers assemble rank-locally and must not touch
2264 // BLACS: initialize() rebuilds the grid whenever the requested block
2265 // size differs from the live one, and that drops the cached Cholesky
2266 // factor. A query side carries one channel per configuration, so it
2267 // requests a block size of 1 against a training grid tiled by D+1 and
2268 // would destroy a factor the caller still needs.
2269 if (!serial_per_rank) {
2270 const int tile_size =
2271 static_cast<int>(detail::storedObservationChannelCount(x_ind));
2272 _st.initialize(tile_size);
2273 }
2274 if (std::getenv("GPR_GEOM_DEBUG"))
2275 std::fprintf(stderr, "[geom] after st.init rss_mb=%.0f\n",
2277 bool replicated = false;
2278 if (!assembleSexpatCovFromGeometry(
2279 *this, backend(), geom, *sexpat_cov_func, x_ind, Ktemp,
2280 /*do_reduce=*/false, serial_per_rank, nullptr, nullptr, nullptr,
2281 nullptr, nullptr, &replicated)) {
2282 if (std::getenv("GPR_GEOM_DEBUG"))
2283 std::fprintf(stderr, "[geom] fallback at apply line %d\n",
2284 __LINE__);
2285 return false;
2286 }
2287 // Reduce the one-owner-per-block sexpat partials BEFORE the
2288 // constant block and noise diagonal: disjoint support keeps the
2289 // Allreduce exact, and the rank-local const + lik adds reproduce
2290 // the single-rank assembly order bit-for-bit at every rank count.
2291 if (!replicated && !serial_per_rank && _st.nprocs() > 1) {
2292 backend().disjoint_sum_bcast(Ktemp.data(),
2293 static_cast<int>(Ktemp.size()));
2294 ++distributed_training_covariance_assemblies_for_testing_;
2295 }
2296 addConstantCovarianceBlock(include_constant ? const_cov_fun.get() : nullptr,
2297 x_ind, x_ind, cov_matrix);
2298 cov_matrix.noalias() += Ktemp;
2299 applyKernelNugget(cov_matrix, n);
2300 if (!include_constant)
2301 detail::addSeparatedConstantNugget(
2302 const_cov_fun.get(), x_ind, kernelNuggetCoefficient(n), cov_matrix);
2303 if (std::getenv("GPR_GEOM_DEBUG"))
2304 std::fprintf(stderr, "[geom] after sexpat rss_mb=%.0f\n",
2306 if (include_noise)
2307 cov_matrix.diagonal() += lik_gaussian->evaluateTrainingVariance(x);
2308 if (std::getenv("GPR_GEOM_DEBUG"))
2309 std::fprintf(stderr, "[geom] after lik rss_mb=%.0f\n",
2311#else
2312 addConstantCovarianceBlock(include_constant ? const_cov_fun.get() : nullptr,
2313 x_ind, x_ind, cov_matrix);
2314 if (!assembleSexpatCovFromGeometry(
2315 *this, backend(), geom, *sexpat_cov_func, x_ind, Ktemp,
2316 /*do_reduce=*/!serial_per_rank, serial_per_rank)) {
2317 if (std::getenv("GPR_GEOM_DEBUG"))
2318 std::fprintf(stderr, "[geom] fallback at apply line %d\n",
2319 __LINE__);
2320 return false;
2321 }
2322 cov_matrix.noalias() += Ktemp;
2323 applyKernelNugget(cov_matrix, n);
2324 if (!include_constant)
2325 detail::addSeparatedConstantNugget(
2326 const_cov_fun.get(), x_ind, kernelNuggetCoefficient(n), cov_matrix);
2327 if (include_noise)
2328 cov_matrix.diagonal() += lik_gaussian->evaluateTrainingVariance(x);
2329#endif
2331 ++training_geometry_apply_calls_for_testing_;
2332 if (log_training_geometry_) {
2333 std::fprintf(stderr, "[geom] apply count=%zu n=%lld blocks=%zu\n",
2334 training_geometry_apply_calls_for_testing_,
2335 static_cast<long long>(geom.n), geom.blocks.size());
2336 }
2337 return true;
2338}
void ordered_sum_bcast(double *data, int count, const MpiContext &context)
static double residentMegabytes() noexcept

◆ evaluateTrainingCrossCovarianceInFactorOrder()

bool gpr::GaussianProcessRegression::evaluateTrainingCrossCovarianceInFactorOrder ( const EigenMatrix & query,
const Eigen::VectorXd & query_ind,
EigenMatrix & cross ) const
nodiscard

Training-by-query cross-covariance written directly in the factor's row order: row r of the channel-major assembly lands at training_permutation_.inv_perm[r] with the same value. False when no permutation is active or the rows are not complete joint observations; cross is then unspecified.

Definition at line 2435 of file CovarianceAssembly.cpp.

2438{
2439#ifdef GPR_LINALG_SCALAPACK
2440 (void)query;
2441 (void)query_ind;
2442 (void)cross;
2443 return false;
2444#else
2445 const auto& placement = training_permutation_.inv_perm;
2446 if (!hasTrainingPermutation() || sexpat_cov_func == nullptr ||
2447 sexpat_cov_func->usesManifoldChart() ||
2448 placement.size() != static_cast<std::size_t>(R_matrix.rows()))
2449 return false;
2450 const Eigen::Index dimensions = 3 * atoms_config.atoms_mov.type.size();
2451 JointOperand left, right;
2452 if (!extractCompleteJointPositions(R_matrix, R_indices, dimensions, left) ||
2453 !extractCompleteJointPositions(query, query_ind, dimensions, right))
2454 return false;
2455 const auto kernel = sexpat_cov_func->assembledOperator();
2456 const EigenMatrix joint = kernel
2457 ? kernel->jointEnergyGradientCrossCovariance(
2458 left.positions, right.positions)
2459 : Sexpat(*sexpat_cov_func)
2460 .jointEnergyGradientCrossCovariance(
2461 left.positions, right.positions);
2462 cross = scatterJointBlockToRows(joint, left, right, placement);
2463 if (const_cov_fun != nullptr && const_cov_fun->getConstSigma2() != 0.0) {
2464 const double const_sigma2 = const_cov_fun->getConstSigma2();
2465 const Eigen::Index row_block =
2466 detail::leadingDerivativeBlockSize(R_indices, 0.0);
2467 const Eigen::Index col_block =
2468 detail::leadingDerivativeBlockSize(query_ind, 0.0);
2469 if (row_block > 0 && col_block > 0 && row_block <= cross.rows() &&
2470 col_block <= cross.cols()) {
2471 for (Eigen::Index col = 0; col < col_block; ++col)
2472 for (Eigen::Index row = 0; row < row_block; ++row)
2473 cross(placement[static_cast<std::size_t>(row)], col) +=
2474 const_sigma2;
2475 }
2476 }
2477 ++factor_order_cross_assemblies_for_testing_;
2478 return true;
2479#endif
2480}

◆ exactNlmlHessianVectorAvailable()

virtual bool gpr::GaussianProcessRegression::exactNlmlHessianVectorAvailable ( ) const
inlinenodiscardvirtualnoexcept

True when the fitted objective is the Gaussian negative log marginal likelihood that evaluateNlmlHessianVector differentiates. False for leave-one-out objectives, for the residual diagonal correction, whose parameter-dependent shift the product omits, while HS-SVD's Q-form objective is active, for ScaLAPACK (the implementation requires a replicated inverse), and for subclasses that rescale the likelihood (Student-t).

Reimplemented in gpr::StudentTProcessRegression.

Definition at line 2401 of file GaussianProcessRegression.h.

2402 {
2403#ifdef GPR_LINALG_SCALAPACK
2404 return false;
2405#else
2406 return hyperparameter_objective_mode_ ==
2408 !use_correction_ &&
2409 !(use_hssvd_backend_ && use_hssvd_objective_contractions_ &&
2410 hssvdObjectiveStampMatches() &&
2411 !hssvd_objective_trace_via_cholesky_);
2412#endif
2413 }

◆ extendTrainingInverseDiagonal()

void gpr::GaussianProcessRegression::extendTrainingInverseDiagonal ( Eigen::Index old_order,
Eigen::Index new_order )
protected

Definition at line 2598 of file Decompose.cpp.

2600{
2601 if (old_order <= 0 || new_order <= old_order ||
2602 training_inverse_diagonal_.size() != old_order) {
2604 return;
2605 }
2606 const Eigen::Index added = new_order - old_order;
2607 EigenMatrix columns = EigenMatrix::Zero(new_order, added);
2608 columns.bottomRows(added).setIdentity();
2609 const auto solver = trainingSolver();
2610 const EigenMatrix whitened = solver.whitenColumns(columns);
2611 const EigenMatrix precision_columns = solver.unwhitenColumns(whitened);
2612 // For K' = [A B; B^T D], Q = K'^-1[:, new] has blocks
2613 // [-A^-1 B S^-1; S^-1], where S = D - B^T A^-1 B = Ls Ls^T.
2614 // The old inverse diagonal gains the row norms of Q_old Ls.
2615 // The lower block of L'^-1 [0; I] is Ls^-1, so a small triangular
2616 // solve forms that product without storing either full inverse.
2617 EigenMatrix correction = precision_columns.topRows(old_order).transpose();
2618 whitened.bottomRows(added)
2619 .transpose()
2620 .template triangularView<Eigen::Upper>()
2621 .solveInPlace(correction);
2622 Eigen::VectorXd diagonal(new_order);
2623 diagonal.head(old_order) = training_inverse_diagonal_ +
2624 correction.colwise().squaredNorm().transpose();
2625 diagonal.tail(added) = precision_columns.bottomRows(added).diagonal();
2626 if (!diagonal.allFinite() || (diagonal.array() <= 0.0).any()) {
2628 return;
2629 }
2630 training_inverse_diagonal_ = std::move(diagonal);
2631 ++inverse_diagonal_appends_for_testing_;
2632}

◆ extractCoordinatesByIndex()

void gpr::GaussianProcessRegression::extractCoordinatesByIndex ( const EigenMatrix & x,
const Eigen::VectorXd & ind_Ddim,
const Index_t ind,
FieldMatrixd & x_loc ) const

Extract coordinates from x using value ind from ind_Ddim.

Note
Exploits the contiguous block structure of ind_Ddim (blocks of N_im identical indices) to perform a single block copy from row ind*N_im instead of scanning all rows. x_loc must be pre-sized to the correct number of rows.

Definition at line 2816 of file CovarianceAssembly.cpp.

2819{
2820 const auto block = observationChannelBlock(ind_Ddim, ind);
2821 const Eigen::Index n_cols = x.cols();
2822 if (ind_Ddim.size() != x.rows() || x_loc.cols() < n_cols)
2823 throw std::invalid_argument(
2824 "coordinate channel block has invalid shape");
2825 if (block.count != x_loc.rows()) {
2826 x_loc.resize(block.count, x_loc.cols());
2827 x_loc.setZero();
2828 }
2829 x_loc.block(0, 0, block.count, n_cols) =
2830 x.block(block.start, 0, block.count, n_cols);
2831}

◆ extractUniqueIndices()

void gpr::GaussianProcessRegression::extractUniqueIndices ( const Eigen::VectorXd & input_ind,
Eigen::VectorXd & output_ind ) const

Extract unique indices from the input vector.

Definition at line 2851 of file CovarianceAssembly.cpp.

2853{
2854 // NOTE: O(n log n) scan; fine for typical sizes (n < 1000)
2855 std::vector<double> unique_ind_loc;
2856
2857 unique_ind_loc.insert(unique_ind_loc.begin(), input_ind.data(),
2858 input_ind.data() + input_ind.size());
2859
2860 // Erase all non-positive values
2861 auto it = std::remove_if(unique_ind_loc.begin(), unique_ind_loc.end(),
2862 [](const double value) { return value <= 0; });
2863 unique_ind_loc.erase(it, unique_ind_loc.end());
2864
2865 // erase all duplicates and sort
2866 sort(unique_ind_loc.begin(), unique_ind_loc.end());
2867 unique_ind_loc.erase(unique(unique_ind_loc.begin(), unique_ind_loc.end()),
2868 unique_ind_loc.end());
2869
2870 Eigen::Map<Eigen::VectorXd> map(unique_ind_loc.data(),
2871 unique_ind_loc.size());
2872 output_ind = map;
2873}

◆ factorEpoch()

std::uint64_t gpr::GaussianProcessRegression::factorEpoch ( ) const
inlinenodiscardnoexcept

Monotone generation of the fitted posterior. Both full-data fits and conditioning on new observations advance the generation.

Definition at line 3169 of file GaussianProcessRegression.h.

3170 {
3171 return factor_epoch_;
3172 }

◆ factorOrderAssembliesForTesting()

std::size_t gpr::GaussianProcessRegression::factorOrderAssembliesForTesting ( ) const
inlinenodiscardnoexcept

Definition at line 863 of file GaussianProcessRegression.h.

864 {
865 return factor_order_assemblies_for_testing_;
866 }

◆ factorOrderCrossAssembliesForTesting()

std::size_t gpr::GaussianProcessRegression::factorOrderCrossAssembliesForTesting ( ) const
inlinenodiscardnoexcept

Definition at line 880 of file GaussianProcessRegression.h.

882 {
883 return factor_order_cross_assemblies_for_testing_;
884 }

◆ failedOptim()

bool gpr::GaussianProcessRegression::failedOptim ( ) const
inlinenodiscardnoexcept

True after the most recent optimize() / optimizeFactorized() call failed to converge. Set by the SCG / Ceres / INLA paths and inspected by the dimer's monitorAndAdaptHyperparameters loop.

Definition at line 3818 of file GaussianProcessRegression.h.

3819 {
3820 return failedOptimizer;
3821 }

◆ findConditionedHessian()

bool gpr::GaussianProcessRegression::findConditionedHessian ( const Eigen::VectorXd & point,
Eigen::MatrixXd & hessian_out ) const
nodiscard

Definition at line 190 of file GaussianProcessRegression.cpp.

192{
193 if (!optimizer_state_) return false;
194 const auto& entries = optimizer_state_->conditioned_hessians;
195 for (auto it = entries.rbegin(); it != entries.rend(); ++it) {
196 if (it->point.size() == point.size() &&
197 (it->point - point).lpNorm<Eigen::Infinity>() <=
198 1e-12 * std::max(1.0, point.lpNorm<Eigen::Infinity>())) {
199 hessian_out = it->hessian;
200 return true;
201 }
202 }
203 return false;
204}

◆ fitActivePosterior()

bool gpr::GaussianProcessRegression::fitActivePosterior ( const Observation & full_observation,
const std::vector< bool > & active_lengths,
bool compare_cartesian_residual = false )
nodiscard

Optimize an independent correction on the appended observations using the conditional likelihood and the configured MAP priors. The fitted background and its output transform remain fixed. False requests a full refit when the correction cannot reach stationarity.

Definition at line 1168 of file ActivePosterior.cpp.

1171{
1172 return fitActivePosteriorImpl(full_observation, active_lengths,
1173 compare_cartesian_residual, true);
1174}

◆ fitGeodesicHeatPrior()

double gpr::GaussianProcessRegression::fitGeodesicHeatPrior ( const Coord & reference_path,
const Observation & training_data )
nodiscard

Fit the nonnegative amplitude of an additive geodesic heat covariance against the current noisy base GP by exact joint energy-gradient marginal likelihood, including its configured diagonal nugget. The base can be inverse-distance Sexpat or a chart pullback; a zero optimum retains that base covariance.

Definition at line 2230 of file GaussianProcessRegression.cpp.

2232{
2233 detail::requireJointTrainingObservation(
2234 training_data, "GaussianProcessRegression::fitGeodesicHeatPrior");
2235 if (!sexpat_cov_func) {
2236 throw std::logic_error(
2237 "geodesic heat prior requires an initialized GP");
2238 }
2239 // An amplitude fit holds the heat metric fixed independently of fitted
2240 // base lengths. The first attachment derives only its initial metric.
2241 const auto retained_heat = sexpat_cov_func->geodesicHeatKernel();
2242 const FieldMatrixd heat_lengths =
2243 retained_heat ? retained_heat->atomisticLengthScales()
2244 : sexpat_cov_func->getAtomisticLengthScaleRef();
2246 aux::AuxiliaryFunctionality auxiliary;
2247 EigenMatrix training_rows;
2248 Eigen::VectorXd training_indices;
2249 Eigen::VectorXd targets;
2251 training_data.R, training_rows, training_indices);
2252 auxiliary.assembleVectorFromEnergyAndGradient(training_data, targets);
2253 subtractPriorMeanFromTargets(training_data.R, training_data.E.size(),
2254 targets);
2255 standardizeTargets(targets, training_data.E.size());
2256
2257 EigenMatrix base_covariance;
2258 evaluateTrainingCovarianceMatrix(training_rows, training_indices,
2259 base_covariance,
2260 /*serial_per_rank=*/true);
2261 const GeodesicHeatEnergyForceKernel unit_geodesic(
2262 reference_path, atoms_config, heat_lengths,
2263 /*covariance_weight=*/1.0);
2264 const EigenMatrix unit_geodesic_features =
2265 unit_geodesic.jointEnergyGradientFeatures(training_data.R);
2266 double weight = 0.0;
2267 if (kernelNuggetCoefficient(training_rows.rows()) > 0.0) {
2268 EigenMatrix unit_geodesic_covariance =
2269 unit_geodesic_features * unit_geodesic_features.transpose();
2270 applyKernelNugget(unit_geodesic_covariance, training_rows.rows());
2272 base_covariance, unit_geodesic_covariance, targets);
2273 } else {
2275 base_covariance, unit_geodesic_features, targets);
2276 }
2277 if (report_level >= 2) {
2278 std::fprintf(stderr,
2279 "[GPR_TRACE_GEODESIC] rows=%lld path=%lld weight=%.17g "
2280 "mean=%.17g scale=%.17g\n",
2281 static_cast<long long>(training_data.R.rows()),
2282 static_cast<long long>(reference_path.rows()), weight,
2283 y_mean_, y_scale_);
2284 }
2285
2286 if (weight > 0.0) {
2288 std::make_shared<const GeodesicHeatEnergyForceKernel>(
2289 unit_geodesic.withCovarianceWeight(weight)));
2290 }
2291 updateModelWithFullData(training_data);
2292 return weight;
2293}
void assembleVectorFromEnergyAndGradient(const gpr::Observation &observation, Eigen::VectorXd &vector)
Combine Energy and gradient into a single Eigen vector.
static double selectWeightFromFeatures(const Eigen::MatrixXd &base_covariance, const Eigen::MatrixXd &unit_geodesic_features, const Eigen::VectorXd &standardized_targets)
static double selectWeight(const Eigen::MatrixXd &base_covariance, const Eigen::MatrixXd &unit_geodesic_covariance, const Eigen::VectorXd &standardized_targets)

◆ fitGeometryBuildsForTesting()

std::size_t gpr::GaussianProcessRegression::fitGeometryBuildsForTesting ( ) const
inlinenodiscardnoexcept

Definition at line 720 of file GaussianProcessRegression.h.

721 {
722 return fit_geometry_builds_for_testing_;
723 }

◆ fitGeometryFor()

const TrainingKernelGeometry * gpr::GaussianProcessRegression::fitGeometryFor ( const EigenMatrix & x,
const Eigen::VectorXd & x_ind ) const
nodiscard

The theta-independent block geometry of the rows a hyperparameter fit evaluates, built on the first objective evaluation of the fit and reused by the rest; nullptr when the rows have no geometry. Keyed on coordinates, observation channels, kernel geometry and execution layout; released when the fit ends.

Definition at line 1795 of file CovarianceAssembly.cpp.

1797{
1798 if (sexpat_cov_func == nullptr || sexpat_cov_func->usesManifoldChart() ||
1799 sexpat_cov_func->usesGeodesicHeatKernel()) {
1801 return nullptr;
1802 }
1803 bool same_layout = true;
1804#ifdef GPR_LINALG_SCALAPACK
1805 if (fit_geometry_cache_.valid && fit_geometry_cache_.has_per_rank_subset) {
1806 auto& distributed = backend().distributed();
1807 distributed.initialize();
1808 same_layout =
1809 fit_geometry_cache_grid_ ==
1810 std::array<int, 4>{distributed.nprow(), distributed.npcol(),
1811 distributed.myrow(), distributed.mycol()};
1812 }
1813#endif
1814 if (fit_geometry_cache_.valid && same_layout &&
1815 fit_geometry_cache_pair_local_ == use_pair_local_tiles_ &&
1816 fit_geometry_cache_rows_.rows() == x.rows() &&
1817 fit_geometry_cache_rows_.cols() == x.cols() &&
1818 fit_geometry_cache_rows_ == x &&
1819 fit_geometry_cache_indices_.size() == x_ind.size() &&
1820 fit_geometry_cache_indices_ == x_ind &&
1821 detail::sameSexpatGeometry(fit_geometry_cache_conf_,
1822 sexpat_cov_func->getConfInfo(),
1823 fit_geometry_cache_far_field_radius_,
1824 sexpat_cov_func->farFieldRadius()))
1825 return &fit_geometry_cache_;
1827 if (!prepareTrainingKernelGeometry(x, x_ind, fit_geometry_cache_,
1828 /*reused=*/true)) {
1829 fit_geometry_cache_.clear();
1830 return nullptr;
1831 }
1832 ++fit_geometry_builds_for_testing_;
1833 fit_geometry_cache_rows_ = x;
1834 fit_geometry_cache_indices_ = x_ind;
1835 fit_geometry_cache_conf_ = sexpat_cov_func->getConfInfo();
1836 fit_geometry_cache_pair_local_ = use_pair_local_tiles_;
1837 fit_geometry_cache_far_field_radius_ = sexpat_cov_func->farFieldRadius();
1838#ifdef GPR_LINALG_SCALAPACK
1839 if (fit_geometry_cache_.has_per_rank_subset) {
1840 const auto& distributed = backend().distributed();
1841 fit_geometry_cache_grid_ = {distributed.nprow(), distributed.npcol(),
1842 distributed.myrow(), distributed.mycol()};
1843 }
1844#endif
1845 return &fit_geometry_cache_;
1846}

◆ fitStepTolerance()

double gpr::GaussianProcessRegression::fitStepTolerance ( ) const
inlinenodiscardnoexcept

The fit's step tolerance: a hyperparameter shift below it is one the optimizer itself treats as no move.

Definition at line 2624 of file GaussianProcessRegression.h.

2625 {
2626 return scg_opt_settings.common.tolerance_sol;
2627 }

◆ fittedHyperparameterInformation()

bool gpr::GaussianProcessRegression::fittedHyperparameterInformation ( Eigen::MatrixXd & information,
Eigen::MatrixXd & directions )

Observed information of the retained fitting density in its free log coordinates. Includes the selected MAP penalty and intrinsic kernel priors, on the actual fit rows and target scale. The columns of directions map these coordinates to packed kernel/noise parameters. Returns false without a supported interior fit snapshot. Uses a separate numerical workspace and preserves the live posterior factor.

Definition at line 867 of file LaplaceSlice.cpp.

869{
870 information.resize(0, 0);
871 directions.resize(0, 0);
872 if (!fitted_hyperparameter_density_ || !sexpat_cov_func || !lik_gaussian)
873 return false;
874 const auto& density = *fitted_hyperparameter_density_;
875 const Eigen::VectorXd current = packInlaHyperparameters();
876 if (current.size() != density.posterior_theta.size() ||
877 !current.allFinite() || use_hssvd_backend_ || use_correction_ ||
878 robust_nu_ > 0.0 || rff_features_requested_ > 0 || rff_auto_ ||
879 active_posterior_ || sexpat_cov_func->usesManifoldChart() ||
880 sexpat_cov_func->usesGeodesicHeatKernel() ||
881 model_profile_ != density.model_profile ||
882 principled_nugget_ != density.principled_nugget ||
883 kappa_max_ != density.kappa_max || !density.kernel ||
884 !detail::sameSexpatGeometry(sexpat_cov_func->getConfInfo(),
885 density.kernel->getConfInfo(),
886 sexpat_cov_func->farFieldRadius(),
887 density.kernel->farFieldRadius()) ||
888 !detail::sameSexpatGeometry(atoms_config, density.configuration)) {
889 return false;
890 }
891 const double epsilon = 64.0 * std::numeric_limits<double>::epsilon();
892 for (Eigen::Index i = 0; i < current.size(); ++i) {
893 if (std::abs(current(i) - density.posterior_theta(i)) >
894 epsilon * std::max(1.0, std::abs(density.posterior_theta(i))))
895 return false;
896 }
897 const auto same_scale = [epsilon](double a, double b) {
898 return std::isfinite(a) && std::isfinite(b) &&
899 std::abs(a - b) <= epsilon * std::max(std::abs(a), std::abs(b));
900 };
901 const double scale2 = density.target_scale * density.target_scale;
902 if ((!density.learn_likelihood_noise &&
903 !same_scale(lik_gaussian->getSigma2(),
904 density.likelihood_sigma2 * scale2)) ||
905 !same_scale(jitter_sigma2, density.jitter_sigma2 * scale2) ||
906 !same_scale(const_cov_fun ? const_cov_fun->getConstSigma2() : 0.0,
907 density.constant_sigma2 * scale2)) {
908 return false;
909 }
910 Eigen::MatrixXd selected =
911 Eigen::MatrixXd::Zero(density.theta.size(), density.free_count);
912 for (Eigen::Index i = 0; i < density.theta.size(); ++i) {
913 const Eigen::Index group =
914 density.parameter_group[static_cast<std::size_t>(i)];
915 if (group >= 0) selected(i, group) = 1.0;
916 }
917 std::unique_ptr<GaussianProcessRegression> objective;
918#if defined(GPR_HAVE_MPI) || defined(GPR_LINALG_SCALAPACK)
919 const auto communication = mpiContext();
920 if (communication.comm != linalg::kMpiCommNull) {
921 objective = std::make_unique<GaussianProcessRegression>(
922 std::make_shared<linalg::MpiCommunicator>(communication.comm));
923 }
924#endif
925 if (!objective) objective = std::make_unique<GaussianProcessRegression>();
926 objective->sexpat_cov_func = std::make_unique<SexpatCF>(*density.kernel);
927 objective->atoms_config = density.configuration;
928 objective->model_profile_ = density.model_profile;
929 objective->use_hssvd_backend_ = false;
930 objective->use_hssvd_objective_contractions_ = false;
931 objective->principled_nugget_ = density.principled_nugget;
932 objective->kappa_max_ = density.kappa_max;
933 objective->lik_gaussian->setSigma2(density.likelihood_sigma2);
934 objective->lik_gaussian->setOptimizeSigma2(density.learn_likelihood_noise);
935 objective->const_cov_fun->setConstSigma2(density.constant_sigma2);
936 objective->jitter_sigma2 = density.jitter_sigma2;
937 objective->scalapack_block_size_ = scalapack_block_size_;
938 objective->scalapack_nprow_ = scalapack_nprow_;
939 objective->configureDistributedTrainingGrid();
940 objective->setParameters(density.theta);
941 EigenMatrix rows;
942 Eigen::VectorXd indices;
943 aux::AuxiliaryFunctionality auxiliary;
944 auxiliary.assembleMatrixOfRepetitiveCoordinates(density.positions, rows,
945 indices);
946 objective->is_decomposed_succesfully =
947 objective->decomposeCovarianceMatrix(rows, indices);
948 if (!objective->is_decomposed_succesfully) return false;
949 objective->calculateMeanPrediction(density.targets);
950 Eigen::MatrixXd hessian;
951 if (!objective->assembleHessianInDirections(indices, rows, density.targets,
952 selected, hessian)) {
953 return false;
954 }
955 // The selected prior penalty is separable; disjoint tie groups preserve
956 // its diagonal reduced Hessian. The kernel's intrinsic prior is in hessian.
957 for (Eigen::Index j = 0; j < selected.cols(); ++j)
959 density.theta, selected.col(j), density.penalty);
960 if (!symmetrizeObservedInformation(hessian)) return false;
961 information = std::move(hessian);
962 directions = std::move(selected);
963 return true;
964}
double mapPenaltyDirectionalCurvature(const Eigen::VectorXd &w, const Eigen::VectorXd &direction, const MapObjectiveConfig &cfg)
constexpr MpiCommType kMpiCommNull
Definition MpiContext.h:56

◆ fittedKernelParameters()

Eigen::VectorXd gpr::GaussianProcessRegression::fittedKernelParameters ( ) const
inlinenodiscard

The kernel hyperparameters as the optimizer sees them (log magnitude, log length scales); empty without a kernel.

Definition at line 2516 of file GaussianProcessRegression.h.

2517 {
2518 return sexpat_cov_func != nullptr ? sexpat_cov_func->combineParameters()
2519 : Eigen::VectorXd();
2520 }

◆ fittedObservations()

const Observation & gpr::GaussianProcessRegression::fittedObservations ( ) const
inlinenodiscardnoexcept

The observations the current posterior is fitted on.

Definition at line 3838 of file GaussianProcessRegression.h.

3839 {
3840 return full_fit_observations_;
3841 }

◆ forgetRgminSessions()

void gpr::GaussianProcessRegression::forgetRgminSessions ( )
noexcept

Drop the rgmin sessions' memory: the next fit starts cold. Called when the parameters move to another basin (an anneal stage).

Definition at line 3637 of file Optimize.cpp.

3638{
3639 scg_stalled_ = false;
3640 scg_stall_scope_ = {};
3641 if (optimizer_state_ == nullptr) return;
3642 optimizer_state_->scg_alternative.forgetSession();
3643 std::visit(
3644 [&](auto& optimizer) {
3645 using Optimizer = std::decay_t<decltype(optimizer)>;
3646 if constexpr (std::is_same_v<Optimizer, funcmin::RgminOpt>)
3647 optimizer.forgetSession();
3648 },
3649 optimizer_state_->optimizer);
3650}

◆ fullCholeskyFactorizationsForTesting()

std::size_t gpr::GaussianProcessRegression::fullCholeskyFactorizationsForTesting ( ) const
inlinenodiscardnoexcept

Definition at line 2705 of file GaussianProcessRegression.h.

2707 {
2708 return full_cholesky_factorizations_for_testing_;
2709 }

◆ fullDataRebuildsForTesting()

std::size_t gpr::GaussianProcessRegression::fullDataRebuildsForTesting ( ) const
inlinenodiscardnoexcept

Definition at line 2802 of file GaussianProcessRegression.h.

2803 {
2804 return full_data_rebuilds_for_testing_;
2805 }

◆ fullFitCoordinateCount()

Eigen::Index gpr::GaussianProcessRegression::fullFitCoordinateCount ( ) const
inlinenodiscardnoexcept

Definition at line 1031 of file GaussianProcessRegression.h.

1032 {
1033 return full_fit_observations_.R.cols();
1034 }

◆ fullFitObservationCount()

Eigen::Index gpr::GaussianProcessRegression::fullFitObservationCount ( ) const
inlinenodiscardnoexcept

Definition at line 1027 of file GaussianProcessRegression.h.

1028 {
1029 return full_fit_observations_.R.rows();
1030 }

◆ getAlpha()

const Eigen::VectorXd & gpr::GaussianProcessRegression::getAlpha ( ) const
inlinenodiscard

Definition at line 3444 of file GaussianProcessRegression.h.

3445 {
3446#ifdef GPR_LINALG_KOKKOS
3448#endif
3449 return a;
3450 }

◆ getAtomsConfig()

const AtomsConfiguration & gpr::GaussianProcessRegression::getAtomsConfig ( ) const
inline

Definition at line 4117 of file GaussianProcessRegression.h.

4118 {
4119 return atoms_config;
4120 }

◆ getChemFactorizedHyperparameters()

bool gpr::GaussianProcessRegression::getChemFactorizedHyperparameters ( ) const
inlinenodiscardnoexcept

Definition at line 1191 of file GaussianProcessRegression.h.

1192 {
1193 return use_chem_factorized_hyper_;
1194 }

◆ getConstantCovarianceFunction() [1/2]

ConstantCF & gpr::GaussianProcessRegression::getConstantCovarianceFunction ( )
inlinenodiscard

Definition at line 3031 of file GaussianProcessRegression.inl.

3032{
3033 return *const_cov_fun;
3034}

◆ getConstantCovarianceFunction() [2/2]

const ConstantCF & gpr::GaussianProcessRegression::getConstantCovarianceFunction ( ) const
inlinenodiscard

Definition at line 3037 of file GaussianProcessRegression.inl.

3038{
3039 return *const_cov_fun;
3040}

◆ getCutlassPluginPath()

const std::string & gpr::GaussianProcessRegression::getCutlassPluginPath ( ) const
inlinenodiscardnoexcept

Definition at line 2077 of file GaussianProcessRegression.h.

2078 {
2079 return cutlass_plugin_path_;
2080 }

◆ getDeltaMaxRatio()

double gpr::GaussianProcessRegression::getDeltaMaxRatio ( ) const
inlinenodiscardnoexcept

Definition at line 2161 of file GaussianProcessRegression.h.

2162 {
2163 return delta_max_ratio_;
2164 }

◆ getDeltaUHMinDiag()

double gpr::GaussianProcessRegression::getDeltaUHMinDiag ( ) const
inlinenodiscardnoexcept

Definition at line 2153 of file GaussianProcessRegression.h.

2154 {
2155 return delta_uh_min_diag_;
2156 }

◆ getDisableOutputNormalization()

bool gpr::GaussianProcessRegression::getDisableOutputNormalization ( ) const
inlinenodiscardnoexcept

Definition at line 1710 of file GaussianProcessRegression.h.

1711 {
1712 return disable_output_normalization_;
1713 }

◆ getDispatchedMapMeanHessianActionsForTesting()

std::size_t gpr::GaussianProcessRegression::getDispatchedMapMeanHessianActionsForTesting ( ) const
nodiscardnoexcept

Count of exact MAP Hessian actions built by dispatch.

Definition at line 162 of file GaussianProcessRegression.cpp.

164{
165 return optimizer_state_->mean_hessian.dispatched_map_hessian_actions;
166}

◆ getHssvdBackend()

bool gpr::GaussianProcessRegression::getHssvdBackend ( ) const
inlinenodiscardnoexcept

Definition at line 1567 of file GaussianProcessRegression.h.

1568 {
1569 return use_hssvd_backend_;
1570 }

◆ getHssvdDualChopTolerance()

double gpr::GaussianProcessRegression::getHssvdDualChopTolerance ( ) const
inlinenodiscardnoexcept

Definition at line 1609 of file GaussianProcessRegression.h.

1610 {
1611 return hssvd_dual_chop_tol_;
1612 }

◆ getHssvdDualLapackRrr()

bool gpr::GaussianProcessRegression::getHssvdDualLapackRrr ( ) const
inlinenodiscardnoexcept

Definition at line 1625 of file GaussianProcessRegression.h.

1626 {
1627 return hssvd_dual_lapack_rrr_;
1628 }

◆ getHssvdDualRandomizedSketch()

int gpr::GaussianProcessRegression::getHssvdDualRandomizedSketch ( ) const
inlinenodiscardnoexcept

Definition at line 1617 of file GaussianProcessRegression.h.

1618 {
1619 return hssvd_dual_randomized_sketch_;
1620 }

◆ getHssvdHessianVectorCallsForTesting()

std::size_t gpr::GaussianProcessRegression::getHssvdHessianVectorCallsForTesting ( ) const
inlinenodiscardnoexcept

Definition at line 1675 of file GaussianProcessRegression.h.

1677 {
1678 return hssvd_hessian_vector_calls_for_testing_;
1679 }

◆ getHssvdLocalActiveSetSize()

int gpr::GaussianProcessRegression::getHssvdLocalActiveSetSize ( ) const
inlinenodiscardnoexcept

Definition at line 1636 of file GaussianProcessRegression.h.

1637 {
1638 return hssvd_local_active_set_size_;
1639 }

◆ getHssvdLocalPosteriorActiveSetSize()

int gpr::GaussianProcessRegression::getHssvdLocalPosteriorActiveSetSize ( ) const
inlinenodiscardnoexcept

Definition at line 1647 of file GaussianProcessRegression.h.

1648 {
1649 return hssvd_local_posterior_active_set_size_;
1650 }

◆ getHssvdObjectiveContractions()

bool gpr::GaussianProcessRegression::getHssvdObjectiveContractions ( ) const
inlinenodiscardnoexcept

Definition at line 1601 of file GaussianProcessRegression.h.

1602 {
1603 return use_hssvd_objective_contractions_;
1604 }

◆ getHutchinsonProbes()

int gpr::GaussianProcessRegression::getHutchinsonProbes ( ) const
inlinenodiscardnoexcept

Definition at line 1556 of file GaussianProcessRegression.h.

1557 {
1558 return hutch_num_probes_;
1559 }

◆ getHyperparameterObjectiveMode()

HyperparameterObjectiveMode gpr::GaussianProcessRegression::getHyperparameterObjectiveMode ( ) const
inlinenodiscardnoexcept

Definition at line 2389 of file GaussianProcessRegression.h.

2391 {
2392 return hyperparameter_objective_mode_;
2393 }

◆ getHyperparameterOptimizationMode()

HyperparameterOptimizationMode gpr::GaussianProcessRegression::getHyperparameterOptimizationMode ( ) const
inlinenodiscardnoexcept

Definition at line 2378 of file GaussianProcessRegression.h.

2379 {
2380 return hyperparameter_optimization_mode_;
2381 }

◆ getHyperparameterOptimizerBackend()

const char * gpr::GaussianProcessRegression::getHyperparameterOptimizerBackend ( ) const
nodiscardnoexcept

Definition at line 227 of file GaussianProcessRegression.cpp.

229{
230 const auto& optimizer = optimizer_state_->optimizer;
231 if (std::holds_alternative<funcmin::RgminScg>(optimizer) ||
232 std::holds_alternative<funcmin::RgminOpt>(optimizer))
233 return "rgmin";
234#ifdef USE_CERES
235 if (std::holds_alternative<funcmin::Ceres>(optimizer)) return "ceres";
236#endif
237 return "builtin";
238}

◆ getJitterSigma2()

double gpr::GaussianProcessRegression::getJitterSigma2 ( ) const
inlinenodiscardnoexcept

Configured numerical diagonal jitter variance.

Definition at line 3307 of file GaussianProcessRegression.h.

3308 {
3309 return jitter_sigma2;
3310 }

◆ getKappaMax()

double gpr::GaussianProcessRegression::getKappaMax ( ) const
inlinenodiscardnoexcept

Definition at line 1959 of file GaussianProcessRegression.h.

1960 {
1961 return kappa_max_;
1962 }

◆ getL()

const EigenMatrix & gpr::GaussianProcessRegression::getL ( ) const
inlinenodiscard

Read-only accessors for training-state members consumed by downstream Laplace / TCOV-INLA helpers.

Definition at line 3415 of file GaussianProcessRegression.h.

3416 {
3417#ifdef GPR_LINALG_KOKKOS
3419#endif
3420 return L;
3421 }

◆ getLaplaceSkipScgThreshold()

double gpr::GaussianProcessRegression::getLaplaceSkipScgThreshold ( ) const
inlinenodiscardnoexcept

Definition at line 1419 of file GaussianProcessRegression.h.

1420 {
1421 return laplace_skip_scg_threshold_;
1422 }

◆ getLengthscaleFloor()

double gpr::GaussianProcessRegression::getLengthscaleFloor ( ) const
inlinenodiscardnoexcept

Definition at line 3327 of file GaussianProcessRegression.h.

3328 {
3329 return lengthscale_floor_;
3330 }

◆ getLengthScaleSeedChemicalFloor()

bool gpr::GaussianProcessRegression::getLengthScaleSeedChemicalFloor ( ) const
inlinenodiscardnoexcept

Definition at line 1806 of file GaussianProcessRegression.h.

1807 {
1808 return ls_seed_chemical_floor_;
1809 }

◆ getLikGaussian() [1/2]

LikGaussian & gpr::GaussianProcessRegression::getLikGaussian ( )
inlinenodiscard

Definition at line 3010 of file GaussianProcessRegression.inl.

3011{
3012 return *lik_gaussian;
3013}

◆ getLikGaussian() [2/2]

const LikGaussian & gpr::GaussianProcessRegression::getLikGaussian ( ) const
inlinenodiscard

Definition at line 3015 of file GaussianProcessRegression.inl.

3016{
3017 return *lik_gaussian;
3018}

◆ getLogRankBlockCholesky()

bool gpr::GaussianProcessRegression::getLogRankBlockCholesky ( ) const
inlinenodiscardnoexcept

Definition at line 2048 of file GaussianProcessRegression.h.

2049 {
2050 return log_rank_block_cholesky_;
2051 }

◆ getLogTrainingGeometry()

bool gpr::GaussianProcessRegression::getLogTrainingGeometry ( ) const
inlinenodiscardnoexcept

Definition at line 2034 of file GaussianProcessRegression.h.

2035 {
2036 return log_training_geometry_;
2037 }

◆ getModelProfile()

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

Definition at line 438 of file GaussianProcessRegression.h.

439 {
440 return model_profile_;
441 }

◆ getNumberOfPotentialCalls()

Index_t gpr::GaussianProcessRegression::getNumberOfPotentialCalls ( ) const
inlinenodiscard

Definition at line 3042 of file GaussianProcessRegression.inl.

3043{
3044 return num_of_potential_calls;
3045}

◆ getNumberOfRepetitiveIndices()

Index_t gpr::GaussianProcessRegression::getNumberOfRepetitiveIndices ( const Eigen::VectorXd & ind_Ddim) const
inline

Count number of the first repetitive indices in ind_Ddim .

Definition at line 48 of file GaussianProcessRegression.inl.

50{
51 Index_t counter = 1;
52 Index_t first_elt = ind_Ddim(0);
53
54 for (Index_t n = 1; n < ind_Ddim.rows(); ++n) {
55 if (ind_Ddim(n) == first_elt)
56 ++counter;
57 else
58 break;
59 }
60
61 return counter;
62}

◆ getObjectiveStationaritySkipAuto()

bool gpr::GaussianProcessRegression::getObjectiveStationaritySkipAuto ( ) const
inlinenodiscardnoexcept

Definition at line 1446 of file GaussianProcessRegression.h.

1447 {
1448 return objective_stationarity_skip_auto_;
1449 }

◆ getObjectiveStationaritySkipThreshold()

double gpr::GaussianProcessRegression::getObjectiveStationaritySkipThreshold ( ) const
inlinenodiscardnoexcept

Definition at line 1428 of file GaussianProcessRegression.h.

1429 {
1430 return laplace_skip_scg_threshold_;
1431 }

◆ getOptimizationSubsetHistory()

int gpr::GaussianProcessRegression::getOptimizationSubsetHistory ( ) const
inlinenodiscardnoexcept

Definition at line 2446 of file GaussianProcessRegression.h.

2447 {
2448 return fps_options.history;
2449 }

◆ getPhysicalTotalDiagonalRegularization()

double gpr::GaussianProcessRegression::getPhysicalTotalDiagonalRegularization ( ) const
inlinenodiscardnoexcept

Physical diagonal regularisation of the training covariance: the Gaussian likelihood variance plus the numerical jitter, both mapped to the physical output frame. The posterior variance of a trained row is bounded by this total, so a force-readiness ceiling built from getSigma2() alone sits below the variance a fully resolved band can reach whenever the jitter is not negligible.

Definition at line 3389 of file GaussianProcessRegression.h.

3390 {
3391 const double likelihood =
3392 lik_gaussian != nullptr ? lik_gaussian->getSigma2() : 0.0;
3393 const double total =
3394 (std::isfinite(likelihood) && likelihood > 0.0 ? likelihood : 0.0) +
3395 (std::isfinite(jitter_sigma2) && jitter_sigma2 > 0.0 ? jitter_sigma2
3396 : 0.0);
3397 if (!(total > 0.0))
3398 return std::isfinite(sigma2) && sigma2 > 0.0 ? sigma2 : 0.0;
3399 return trainingToPhysicalNoiseVariance(total);
3400 }

◆ getPrincipledNugget()

bool gpr::GaussianProcessRegression::getPrincipledNugget ( ) const
inlinenodiscardnoexcept

Definition at line 1948 of file GaussianProcessRegression.h.

1949 {
1950 return principled_nugget_;
1951 }

◆ getProfileEnergySplit()

bool gpr::GaussianProcessRegression::getProfileEnergySplit ( ) const
inlinenodiscardnoexcept

Definition at line 1527 of file GaussianProcessRegression.h.

1528 {
1529 return profile_energy_split_;
1530 }

◆ getProfileGradientSplit()

bool gpr::GaussianProcessRegression::getProfileGradientSplit ( ) const
inlinenodiscardnoexcept

Definition at line 1536 of file GaussianProcessRegression.h.

1537 {
1538 return profile_gradient_split_;
1539 }

◆ getProfilePredictMean()

bool gpr::GaussianProcessRegression::getProfilePredictMean ( ) const
inlinenodiscardnoexcept

Definition at line 1518 of file GaussianProcessRegression.h.

1519 {
1520 return profile_predict_mean_;
1521 }

◆ getRFFFeatures()

int gpr::GaussianProcessRegression::getRFFFeatures ( ) const
inlinenodiscardnoexcept

Definition at line 2177 of file GaussianProcessRegression.h.

2178 {
2179 return rff_features_;
2180 }

◆ getRFFFeaturesRequested()

int gpr::GaussianProcessRegression::getRFFFeaturesRequested ( ) const
inlinenodiscardnoexcept

Definition at line 2199 of file GaussianProcessRegression.h.

2200 {
2201 return rff_features_requested_;
2202 }

◆ getRIndices()

const Eigen::VectorXd & gpr::GaussianProcessRegression::getRIndices ( ) const
inlinenodiscardnoexcept

Definition at line 3455 of file GaussianProcessRegression.h.

3456 {
3457 return R_indices;
3458 }

◆ getRMatrix()

const EigenMatrix & gpr::GaussianProcessRegression::getRMatrix ( ) const
inlinenodiscardnoexcept

Definition at line 3451 of file GaussianProcessRegression.h.

3452 {
3453 return R_matrix;
3454 }

◆ getScalapackBlockSize()

int gpr::GaussianProcessRegression::getScalapackBlockSize ( ) const
inlinenodiscardnoexcept

Definition at line 2058 of file GaussianProcessRegression.h.

2059 {
2060 return scalapack_block_size_;
2061 }

◆ getScalapackNprow()

int gpr::GaussianProcessRegression::getScalapackNprow ( ) const
inlinenodiscardnoexcept

Definition at line 2068 of file GaussianProcessRegression.h.

2069 {
2070 return scalapack_nprow_;
2071 }

◆ getSexpAtCovarianceFunction() [1/2]

SexpatCF & gpr::GaussianProcessRegression::getSexpAtCovarianceFunction ( )
inlinenodiscard

Definition at line 3020 of file GaussianProcessRegression.inl.

3021{
3022 return *sexpat_cov_func;
3023}

◆ getSexpAtCovarianceFunction() [2/2]

const SexpatCF & gpr::GaussianProcessRegression::getSexpAtCovarianceFunction ( ) const
inlinenodiscard

Definition at line 3025 of file GaussianProcessRegression.inl.

3027{
3028 return *sexpat_cov_func;
3029}

◆ getSigma2()

double gpr::GaussianProcessRegression::getSigma2 ( ) const
inlinenodiscardnoexcept

Live physical output-noise variance of the fitted model (the value the resolution-limit admission threshold and RFF path consume).

Definition at line 3378 of file GaussianProcessRegression.h.

3379 {
3380 return sigma2;
3381 }

◆ getSVGDConfig()

const laplace::SteinVariationalConfig & gpr::GaussianProcessRegression::getSVGDConfig ( ) const
inlinenodiscardnoexcept

Definition at line 4426 of file GaussianProcessRegression.h.

4428 {
4429 return svgd_config_;
4430 }

◆ getUncertaintyMode()

UncertaintyMode gpr::GaussianProcessRegression::getUncertaintyMode ( ) const
inline

Definition at line 1360 of file GaussianProcessRegression.h.

1361 {
1362 return uncertainty_mode_;
1363 }

◆ getUseAlphaKLaplaceMean()

bool gpr::GaussianProcessRegression::getUseAlphaKLaplaceMean ( ) const
inlinenodiscardnoexcept

Definition at line 1410 of file GaussianProcessRegression.h.

1411 {
1412 return use_alpha_k_laplace_mean_;
1413 }

◆ getUseAlphaKPredictMean()

bool gpr::GaussianProcessRegression::getUseAlphaKPredictMean ( ) const
inlinenodiscardnoexcept

Definition at line 1400 of file GaussianProcessRegression.h.

1401 {
1402 return use_alpha_k_predict_mean_;
1403 }

◆ getUseDeltaMethod()

bool gpr::GaussianProcessRegression::getUseDeltaMethod ( ) const
inlinenodiscardnoexcept

Definition at line 2125 of file GaussianProcessRegression.h.

2126 {
2127 return use_delta_method_;
2128 }

◆ getUseFFPriorMean()

bool gpr::GaussianProcessRegression::getUseFFPriorMean ( ) const
inlinenodiscardnoexcept

Definition at line 2025 of file GaussianProcessRegression.h.

2026 {
2027 return use_ff_prior_mean_;
2028 }

◆ getUseLsPrior()

bool gpr::GaussianProcessRegression::getUseLsPrior ( ) const
inlinenodiscardnoexcept

Definition at line 1779 of file GaussianProcessRegression.h.

1780 {
1781 return use_ls_prior_;
1782 }

◆ getUsePsisDeterministicGrid()

bool gpr::GaussianProcessRegression::getUsePsisDeterministicGrid ( ) const
inlinenodiscardnoexcept

Definition at line 2107 of file GaussianProcessRegression.h.

2108 {
2109 return psis_laplace_opts_.deterministic_axial_grid;
2110 }

◆ getUsePsisLaplace()

bool gpr::GaussianProcessRegression::getUsePsisLaplace ( ) const
inlinenodiscardnoexcept

Definition at line 2091 of file GaussianProcessRegression.h.

2092 {
2093 return use_psis_laplace_;
2094 }

◆ getUseTrainingGeometryHandle()

bool gpr::GaussianProcessRegression::getUseTrainingGeometryHandle ( ) const
inlinenodiscardnoexcept

Definition at line 1509 of file GaussianProcessRegression.h.

1510 {
1511 return use_training_geometry_handle_;
1512 }

◆ getUseZBLPriorMean()

bool gpr::GaussianProcessRegression::getUseZBLPriorMean ( ) const
inlinenodiscardnoexcept

Definition at line 1969 of file GaussianProcessRegression.h.

1970 {
1971 return use_zbl_prior_mean_;
1972 }

◆ gradientReplicatedInverseEntriesForTesting()

std::size_t gpr::GaussianProcessRegression::gradientReplicatedInverseEntriesForTesting ( ) const
inlinenodiscardnoexcept

Definition at line 2617 of file GaussianProcessRegression.h.

2619 {
2620 return gradient_replicated_inverse_entries_for_testing_;
2621 }

◆ hasActivePosterior()

bool gpr::GaussianProcessRegression::hasActivePosterior ( ) const
inlinenodiscardnoexcept

Definition at line 3240 of file GaussianProcessRegression.h.

3241 {
3242 return static_cast<bool>(active_posterior_);
3243 }

◆ hasBeenOptimized()

bool gpr::GaussianProcessRegression::hasBeenOptimized ( ) const
inline

Definition at line 3296 of file GaussianProcessRegression.h.

3297 {
3298 return has_been_optimized_;
3299 }

◆ hasDevicePosterior()

bool gpr::GaussianProcessRegression::hasDevicePosterior ( ) const
nodiscardprotectednoexcept

Definition at line 294 of file DevicePosterior.cpp.

295{
296 return false;
297}

◆ hasObjectiveStationarityHessianForTesting()

bool gpr::GaussianProcessRegression::hasObjectiveStationarityHessianForTesting ( ) const
inlinenodiscardnoexcept

Definition at line 1466 of file GaussianProcessRegression.h.

1468 {
1469 return objective_stationarity_hessian_valid_;
1470 }

◆ hasObjectiveStationarityInverseHessianForTesting()

bool gpr::GaussianProcessRegression::hasObjectiveStationarityInverseHessianForTesting ( ) const
inlinenodiscardnoexcept

Definition at line 1471 of file GaussianProcessRegression.h.

1473 {
1474 return objective_stationarity_inverse_hessian_valid_;
1475 }

◆ hasPendingActivePosteriorRefit()

bool gpr::GaussianProcessRegression::hasPendingActivePosteriorRefit ( ) const
inlinenodiscardnoexcept

Definition at line 652 of file GaussianProcessRegression.h.

653 {
654 return !active_refit_lengths_.empty();
655 }

◆ hasPendingResidualModelRefit()

bool gpr::GaussianProcessRegression::hasPendingResidualModelRefit ( ) const
inlinenodiscardnoexcept

Model expansion for a measured error despite small force uncertainty. This does not certify the force or restrict fitting to active lengths.

Definition at line 658 of file GaussianProcessRegression.h.

659 {
660 return residual_model_refit_;
661 }

◆ hasReusableHssvdPosterior()

bool gpr::GaussianProcessRegression::hasReusableHssvdPosterior ( ) const
inlinenodiscardnoexcept

Definition at line 1593 of file GaussianProcessRegression.h.

1594 {
1595 return !active_posterior_ && hasMaterializedHssvdBackground();
1596 }

◆ hasTrainingCholeskyFactor()

bool gpr::GaussianProcessRegression::hasTrainingCholeskyFactor ( Eigen::Index expected_rows) const
nodiscardnoexcept

A usable training Cholesky factor exists for the linalg::forward_solve / back_solve consumers: either the dense member L matches the training rows, or (ScaLAPACK backend) the factor lives replicated-distributed in the DistributedState cache and is owned by this model. The scalapack cholesky() caches the factor and empties the dense member, and every triangular solve consults the cache first, so an empty dense L with a matching cache is fully functional; guards that compare getL().rows() against the training size bail on exactly that valid state.

Definition at line 196 of file Decompose.cpp.

198{
199 const Eigen::Index n = activeFactorOrder(expected_rows);
200 if (n <= 0) return false;
201#ifdef GPR_LINALG_KOKKOS
203 resident_training_factor_->order() == n)
204 return true;
205#endif
206 if (L.rows() == n && L.cols() == n) return true;
207#ifdef GPR_LINALG_SCALAPACK
208 if (training_cholesky_is_distributed_) {
209 const auto& st = backend().distributed();
210 return st.cached_L_owned_by(this) &&
211 st.cached_n() == static_cast<int>(n);
212 }
213#endif
214 return false;
215}

◆ hasTrainingPermutation()

bool gpr::GaussianProcessRegression::hasTrainingPermutation ( ) const
nodiscard

◆ holdLengthScalesUnresolvedBySubset()

std::vector< std::size_t > gpr::GaussianProcessRegression::holdLengthScalesUnresolvedBySubset ( const Observation & subset)

Hold, for the next fit, the length scales a pooled subset does not resolve: its inverse-distance features of that pair type span less than one length scale. Returns the held mask slots.

Definition at line 1426 of file Optimize.cpp.

1428{
1429 // A pooled subset is the search's own footprint, and those rows can
1430 // lie a few thousandths of an angstrom apart. Fitting a length scale
1431 // they do not resolve moves it by an order of magnitude on the priors
1432 // alone; the posterior conditioned at those parameters is flat beside
1433 // the rows, and its curvature is the prior mean's. Such a length scale
1434 // keeps its value. Signal and likelihood variances still fit.
1435 if (!sexpat_cov_func || sexpat_cov_func->usesManifoldChart() ||
1436 sexpat_cov_func->usesGeodesicHeatKernel())
1437 return {};
1438 std::vector<bool> resolved =
1439 lengthScalesResolvedByRows(*sexpat_cov_func, subset.R);
1440 const Eigen::Index count = static_cast<Eigen::Index>(resolved.size());
1441 if (lengthScaleTiesActive(count)) {
1442 // A tie group moves as one length scale.
1443 std::vector<bool> group(resolved.size(), false);
1444 for (Eigen::Index t = 0; t < count; ++t)
1445 if (resolved[static_cast<std::size_t>(t)])
1446 group[static_cast<std::size_t>(
1447 length_scale_ties_.leader[static_cast<std::size_t>(t)])] =
1448 true;
1449 for (Eigen::Index t = 0; t < count; ++t)
1450 resolved[static_cast<std::size_t>(t)] =
1451 group[static_cast<std::size_t>(
1452 length_scale_ties_.leader[static_cast<std::size_t>(t)])];
1453 }
1454 if (std::all_of(resolved.begin(), resolved.end(),
1455 [](bool value) { return value; }))
1456 return {};
1457 std::vector<bool>& mask = scg_opt_settings.active_parameters;
1458 if (mask.empty())
1459 mask = fullRefitMask(sexpat_cov_func.get(), lik_gaussian.get());
1460 if (mask.size() < 1 + resolved.size()) return {};
1461 std::vector<std::size_t> held_slots;
1462 for (Eigen::Index k = 0; k < count; ++k) {
1463 const std::size_t slot = static_cast<std::size_t>(1 + k);
1464 if (resolved[static_cast<std::size_t>(k)] || !mask[slot]) continue;
1465 mask[slot] = false;
1466 held_slots.push_back(slot);
1467 }
1468 const auto held = held_slots.size();
1469 if (held > 0 && report_level >= 1)
1470 log_man << "Hyperparameter subset: " << subset.R.rows()
1471 << " rows span less than one length scale in " << held << " of "
1472 << count
1473 << " pair types; those length scales keep their values.\n";
1474 return held_slots;
1475}

◆ hssvdAppendUpdatesForTesting()

std::size_t gpr::GaussianProcessRegression::hssvdAppendUpdatesForTesting ( ) const
inlinenodiscardnoexcept

Definition at line 2785 of file GaussianProcessRegression.h.

2786 {
2787 return hssvd_append_updates_for_testing_;
2788 }

◆ hssvdBasisConditionNumberForTesting()

double gpr::GaussianProcessRegression::hssvdBasisConditionNumberForTesting ( ) const
inlinenodiscardnoexcept

Definition at line 2825 of file GaussianProcessRegression.h.

2826 {
2827 return hssvd_basis_valid_ ? hssvd_basis_.conditionNumber() : 0.0;
2828 }

◆ hssvdBasisForTesting()

const StableBasisND & gpr::GaussianProcessRegression::hssvdBasisForTesting ( ) const
inlinenodiscardnoexcept

Definition at line 2816 of file GaussianProcessRegression.h.

2817 {
2818 return hssvd_basis_;
2819 }

◆ hssvdBasisObservationCountForTesting()

Eigen::Index gpr::GaussianProcessRegression::hssvdBasisObservationCountForTesting ( ) const
inlinenodiscardnoexcept

Definition at line 2806 of file GaussianProcessRegression.h.

2808 {
2809 return hssvd_basis_valid_ ? hssvd_basis_.numObs() : 0;
2810 }

◆ hssvdDualAlphaKPreparedForTesting()

bool gpr::GaussianProcessRegression::hssvdDualAlphaKPreparedForTesting ( ) const
inlinenodiscardnoexcept

Definition at line 2966 of file GaussianProcessRegression.h.

2967 {
2968 return hssvd_dual_alpha_k_prepared_.valid;
2969 }

◆ hssvdDualForceWeightColsForTesting()

Eigen::Index gpr::GaussianProcessRegression::hssvdDualForceWeightColsForTesting ( ) const
inlinenodiscardnoexcept

Definition at line 2961 of file GaussianProcessRegression.h.

2963 {
2964 return hssvd_dual_force_jacobian_weights_.cols();
2965 }

◆ hssvdDualForceWeightRowsForTesting()

Eigen::Index gpr::GaussianProcessRegression::hssvdDualForceWeightRowsForTesting ( ) const
inlinenodiscardnoexcept

Definition at line 2956 of file GaussianProcessRegression.h.

2958 {
2959 return hssvd_dual_force_jacobian_weights_.rows();
2960 }

◆ hssvdDualKernelActiveForTesting()

bool gpr::GaussianProcessRegression::hssvdDualKernelActiveForTesting ( ) const
inlinenodiscardnoexcept

Definition at line 3059 of file GaussianProcessRegression.h.

3060 {
3061 return hssvd_dual_kernel_;
3062 }

◆ hssvdEnergyDesign()

bool gpr::GaussianProcessRegression::hssvdEnergyDesign ( const FieldMatrixd & query,
Eigen::VectorXd & design,
Eigen::VectorXd & coeff ) const
nodiscard

Design row and reduced coefficients of one HS-SVD energy prediction. The standardized energy is their dot product.

Definition at line 1033 of file Decompose.cpp.

1036{
1037 if (!use_hssvd_backend_ || !hssvd_basis_valid_ || query.rows() != 1)
1038 return false;
1039 if (hssvd_dual_kernel_) {
1040 if (hssvd_dual_predict_weights_.size() == 0 || R_matrix.rows() == 0)
1041 return false;
1042 aux::AuxiliaryFunctionality aux;
1043 EigenMatrix query_rows;
1044 Eigen::VectorXd query_ind;
1045 aux.assembleMatrixOfRepetitiveCoordinates(query, query_rows, query_ind);
1046 EigenMatrix cross;
1048 R_matrix, query_rows, R_indices, query_ind, cross,
1049 /*serial_per_rank=*/true);
1050 if (cross.rows() != hssvd_dual_predict_weights_.size() ||
1051 cross.cols() < 1)
1052 return false;
1053 design = cross.col(0);
1054 coeff = hssvd_dual_predict_weights_;
1055 return true;
1056 }
1057 if (hssvd_p_.size() == 0 || hssvd_l_feat_.size() == 0) return false;
1058 const Eigen::Index dfeat = hssvd_l_feat_.size();
1059 Coord xr = query.row(0);
1060 Eigen::VectorXd q;
1061 EigenMatrix J;
1063 xr, sexpat_cov_func->getConfInfo(), q, J);
1064 Eigen::MatrixXd Qtil(1, dfeat);
1065 for (Eigen::Index k = 0; k < dfeat; ++k)
1066 Qtil(0, k) = (q(k) - hssvd_mean_feat_(k)) / hssvd_l_feat_(k);
1067 Eigen::MatrixXd Uq;
1068 Eigen::MatrixXd Rq;
1069 StableBasisND::projectToAffineSpan(Qtil, hssvd_feature_basis_, Uq, Rq);
1070 design = hssvd_basis_.energyAffineDesignRow(Uq, Rq);
1071 coeff = hssvd_p_;
1072 return design.size() == coeff.size() && design.size() > 0;
1073}
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).
static void projectToAffineSpan(const Eigen::MatrixXd &centered_X, const Eigen::MatrixXd &basis, Eigen::MatrixXd &coords, Eigen::MatrixXd &residuals)

◆ hssvdFullFactorizationsForTesting()

std::size_t gpr::GaussianProcessRegression::hssvdFullFactorizationsForTesting ( ) const
inlinenodiscardnoexcept

Definition at line 2794 of file GaussianProcessRegression.h.

2795 {
2796 return hssvd_full_factorizations_for_testing_;
2797 }

◆ hssvdLastLocalActiveSetConditionNumberForTesting()

double gpr::GaussianProcessRegression::hssvdLastLocalActiveSetConditionNumberForTesting ( ) const
inlinenodiscardnoexcept

Definition at line 3120 of file GaussianProcessRegression.h.

3122 {
3123 return hssvd_last_local_active_set_condition_for_testing_;
3124 }

◆ hssvdLastLocalActiveSetConfigCountForTesting()

Eigen::Index gpr::GaussianProcessRegression::hssvdLastLocalActiveSetConfigCountForTesting ( ) const
inlinenodiscardnoexcept

Definition at line 3110 of file GaussianProcessRegression.h.

3112 {
3113 return hssvd_last_local_active_set_config_count_for_testing_;
3114 }

◆ hssvdLastLocalActiveSetObservationCountForTesting()

Eigen::Index gpr::GaussianProcessRegression::hssvdLastLocalActiveSetObservationCountForTesting ( ) const
inlinenodiscardnoexcept

Definition at line 3116 of file GaussianProcessRegression.h.

3117 {
3118 return hssvd_last_local_active_set_observation_count_for_testing_;
3119 }

◆ hssvdLastLocalPosteriorConditionNumberForTesting()

double gpr::GaussianProcessRegression::hssvdLastLocalPosteriorConditionNumberForTesting ( ) const
inlinenodiscardnoexcept

Definition at line 3135 of file GaussianProcessRegression.h.

3137 {
3138 return hssvd_last_local_posterior_condition_for_testing_;
3139 }

◆ hssvdLastLocalPosteriorConfigCountForTesting()

Eigen::Index gpr::GaussianProcessRegression::hssvdLastLocalPosteriorConfigCountForTesting ( ) const
inlinenodiscardnoexcept

Definition at line 3125 of file GaussianProcessRegression.h.

3127 {
3128 return hssvd_last_local_posterior_config_count_for_testing_;
3129 }

◆ hssvdLastLocalPosteriorObservationCountForTesting()

Eigen::Index gpr::GaussianProcessRegression::hssvdLastLocalPosteriorObservationCountForTesting ( ) const
inlinenodiscardnoexcept

Definition at line 3131 of file GaussianProcessRegression.h.

3132 {
3133 return hssvd_last_local_posterior_observation_count_for_testing_;
3134 }

◆ hssvdLocalPosteriorCovarianceForTesting()

bool gpr::GaussianProcessRegression::hssvdLocalPosteriorCovarianceForTesting ( const EigenMatrix & positions,
const EigenMatrix & prior,
EigenMatrix & K_post )
nodiscard

The local HS-SVD posterior covariance of positions against a caller-supplied prior block, as calculateObservationPosteriorCovariance reaches it, so a test can pose a prior the model never forms.

Definition at line 1851 of file Variance.cpp.

1853{
1854 EigenMatrix query_rows;
1855 Eigen::VectorXd query_indices;
1856 aux::AuxiliaryFunctionality{}.assembleMatrixOfRepetitiveCoordinates(
1857 positions, query_rows, query_indices);
1858 return calculateObservationPosteriorCovarianceHssvdLocal(
1859 positions, query_rows, query_indices, prior, K_post);
1860}

◆ hssvdObjectiveBasisValidForTesting()

bool gpr::GaussianProcessRegression::hssvdObjectiveBasisValidForTesting ( ) const
inlinenodiscard

Definition at line 2889 of file GaussianProcessRegression.h.

2890 {
2891 return ensureHssvdObjectiveTraceBasis();
2892 }

◆ hssvdObjectiveConditionNumberForTesting()

double gpr::GaussianProcessRegression::hssvdObjectiveConditionNumberForTesting ( ) const
inlinenodiscard

Definition at line 2910 of file GaussianProcessRegression.h.

2911 {
2912 return ensureHssvdObjectiveTraceBasis() ? 1.0 : 0.0;
2913 }

◆ hssvdObjectivePendingReplicatedEntriesForTesting()

Eigen::Index gpr::GaussianProcessRegression::hssvdObjectivePendingReplicatedEntriesForTesting ( ) const
inlinenodiscardnoexcept

Definition at line 2899 of file GaussianProcessRegression.h.

2900 {
2901 return hssvd_objective_pending_covariance_.size();
2902 }

◆ hssvdObjectiveRankForTesting()

Eigen::Index gpr::GaussianProcessRegression::hssvdObjectiveRankForTesting ( ) const
inlinenodiscard

Definition at line 2914 of file GaussianProcessRegression.h.

2915 {
2916 return ensureHssvdObjectiveTraceBasis()
2917 ? hssvd_objective_trace_basis_.cols()
2918 : 0;
2919 }

◆ hssvdObjectiveTraceBasisMaterializedForTesting()

bool gpr::GaussianProcessRegression::hssvdObjectiveTraceBasisMaterializedForTesting ( ) const
inlinenodiscardnoexcept

Definition at line 2893 of file GaussianProcessRegression.h.

2895 {
2896 return hssvd_objective_trace_basis_.size() > 0;
2897 }

◆ hssvdObjectiveTraceInvNoiseForTesting()

double gpr::GaussianProcessRegression::hssvdObjectiveTraceInvNoiseForTesting ( ) const
inlinenodiscardnoexcept

Definition at line 2920 of file GaussianProcessRegression.h.

2921 {
2922 return hssvd_objective_trace_inv_noise_;
2923 }

◆ hssvdObjectiveTraceViaCholeskyForTesting()

bool gpr::GaussianProcessRegression::hssvdObjectiveTraceViaCholeskyForTesting ( ) const
inlinenodiscardnoexcept

Definition at line 2934 of file GaussianProcessRegression.h.

2935 {
2936 return hssvd_objective_trace_via_cholesky_;
2937 }

◆ hssvdObjectiveUsesDirectInverseForTesting()

bool gpr::GaussianProcessRegression::hssvdObjectiveUsesDirectInverseForTesting ( ) const
inlinenodiscardnoexcept

Definition at line 2929 of file GaussianProcessRegression.h.

2931 {
2932 return hssvd_objective_trace_direct_inverse_;
2933 }

◆ hssvdVarianceCalibrationFactorForTesting()

double gpr::GaussianProcessRegression::hssvdVarianceCalibrationFactorForTesting ( ) const
inlinenodiscardnoexcept

Definition at line 2829 of file GaussianProcessRegression.h.

2831 {
2833 }

◆ hyperparameterDataTermScale()

virtual double gpr::GaussianProcessRegression::hyperparameterDataTermScale ( ) const
inlineprotectedvirtual

Factor on the data-fit term of the hyperparameter gradient, applied as the square root on alpha so that alpha^T dK alpha and the likelihood noise term scale together. The Gaussian marginal likelihood is 1. A model whose energy weighs the data term differently overrides it, and the geometry, permutation and dense gradient routes stay shared.

Reimplemented in gpr::StudentTProcessRegression.

Definition at line 3565 of file GaussianProcessRegression.h.

3566 {
3567 return 1.0;
3568 }

◆ hyperparameterEnergyIsGaussian()

virtual bool gpr::GaussianProcessRegression::hyperparameterEnergyIsGaussian ( ) const
inlineprotectedvirtual

False when evaluateEnergy(x, x_ind, y) is not the Gaussian marginal likelihood, so the HS-SVD energy that reads only the geometry cannot stand in for it.

Reimplemented in gpr::StudentTProcessRegression.

Definition at line 3581 of file GaussianProcessRegression.h.

3582 {
3583 return true;
3584 }

◆ hyperparameterOptimizationModeName()

const char * gpr::GaussianProcessRegression::hyperparameterOptimizationModeName ( ) const
inlinenodiscardnoexcept

Name of the hyperparameter fit in force, for the run report.

Definition at line 3015 of file GaussianProcessRegression.h.

3017 {
3018 switch (hyperparameter_optimization_mode_) {
3020 return "inla";
3022 return "map_lbfgs";
3024 return "rgmin_scg";
3026 return "rgmin";
3028 return "scg";
3029 }
3030 return "unknown";
3031 }

◆ incrementalCholeskyUpdatesForTesting()

std::size_t gpr::GaussianProcessRegression::incrementalCholeskyUpdatesForTesting ( ) const
inlinenodiscardnoexcept

Definition at line 2700 of file GaussianProcessRegression.h.

2702 {
2703 return incremental_cholesky_updates_for_testing_;
2704 }

◆ inferInternalCoordinateLengthScale()

std::optional< double > gpr::GaussianProcessRegression::inferInternalCoordinateLengthScale ( const geometry::InternalCoordinateChart & chart) const
nodiscard

Match one isotropic intrinsic length to the fitted global kernel's mean force variance in a nonredundant molecular tangent space. Returns no value when the chart or projected force metric is not positive and finite.

Definition at line 2296 of file GaussianProcessRegression.cpp.

2298{
2299 if (!sexpat_cov_func || !chart.valid() ||
2300 sexpat_cov_func->getLengthScaleRef().size() <= 0) {
2301 return std::nullopt;
2302 }
2303 // Allocated unit lengths reserve parameter slots. A data-derived seed or
2304 // a fitted background supplies the physical metric for a local chart.
2305 if (!(seed_length_scale_ > 0.0) && !has_been_optimized_ &&
2306 full_fit_observations_.R.rows() == 0) {
2307 return std::nullopt;
2308 }
2309 const Eigen::Index dimensions = chart.anchor().size();
2310 const Eigen::Index rank = chart.rank();
2311 if (dimensions <= 0 || rank <= 0 ||
2312 chart.tangentBasis().rows() != dimensions) {
2313 return std::nullopt;
2314 }
2315
2316 EigenMatrix positions(1, dimensions);
2317 positions.row(0) = chart.anchor().transpose();
2318 // The chart length belongs to the base component. An independently
2319 // weighted heat covariance cannot change its force-variance match.
2320 EigenMatrix prior;
2321 if (sexpat_cov_func->usesManifoldChart())
2322 prior =
2323 sexpat_cov_func->manifoldJointEnergyGradientCovariance(positions);
2324 else
2325 prior =
2326 Sexpat(*sexpat_cov_func).jointEnergyGradientCovariance(positions);
2327 if (prior.rows() != dimensions + 1 || prior.cols() != dimensions + 1 ||
2328 !prior.allFinite()) {
2329 return std::nullopt;
2330 }
2331
2332 const EigenMatrix force_covariance =
2333 prior.block(1, 1, dimensions, dimensions);
2334 const EigenMatrix tangent_covariance = chart.tangentBasis().transpose() *
2335 force_covariance *
2336 chart.tangentBasis();
2337 const double tangent_trace = tangent_covariance.trace();
2338 const double signal_variance = sexpat_cov_func->getMagnSigma2();
2339 if (!(tangent_trace > 0.0) || !std::isfinite(tangent_trace) ||
2340 !(signal_variance > 0.0) || !std::isfinite(signal_variance)) {
2341 return std::nullopt;
2342 }
2343 const double length_squared =
2344 signal_variance * static_cast<double>(rank) / tangent_trace;
2345 if (!(length_squared > 0.0) || !std::isfinite(length_squared)) {
2346 return std::nullopt;
2347 }
2348 return std::sqrt(length_squared);
2349}

◆ initialize()

void gpr::GaussianProcessRegression::initialize ( const InputParameters & parameters,
const AtomsConfiguration & conf_info )

Initialize GPR class.

Parameters
conf_infoInformation about the configurations necessary for the GPR model
parametersStructure of parameters

Definition at line 1157 of file GaussianProcessRegression.cpp.

1159{
1161 if (atomic_environment_model_) invalidateLikelihoodNoiseDependentState();
1162 atomic_environment_cutoff_ = std::isfinite(parameters.actdist_fro.value) &&
1163 parameters.actdist_fro.value > 0.0
1164 ? parameters.actdist_fro.value
1165 : 4.0;
1166 this->atoms_config = conf_info;
1167 configureLengthScaleTies(conf_info);
1168 if (parameters.gp_nonperiodic.value) {
1169 std::fill(std::begin(this->atoms_config.cell),
1170 std::end(this->atoms_config.cell), 0.0);
1171 } else if (geometry::cellIsZero(this->atoms_config.cell)) {
1172 geometry::copyMicLattice(this->atoms_config.cell,
1173 parameters.cell_dimensions.value);
1174 }
1175 // Open axes carry zero rows, which every PairBox reads as open.
1176 geometry::zeroOpenAxes(this->atoms_config.cell,
1177 {parameters.cell_periodic.value[0] != 0,
1178 parameters.cell_periodic.value[1] != 0,
1179 parameters.cell_periodic.value[2] != 0});
1180 configureZBLPriorMean(this->atoms_config);
1181 configureFFPriorMean(this->atoms_config);
1182 fps_options.history = parameters.fps_history.value;
1183 fps_options.metric = parameters.fps_metric.value;
1184 // Classic joint [E, F] profiles evaluate PriorSqrtt, which divides by nu,
1185 // and both profiles read s2 for prior scales.
1186 if (usesClassicJointEnergyForcePrior(model_profile_) &&
1187 (!sexpat_cov_func || !sexpat_cov_func->useLogNormalMagnPrior())) {
1189 parameters.prior_nu.value);
1190 }
1192 parameters.prior_s2.value);
1193 PriorBase prior_parameters;
1194
1195 use_precision_ = parameters.use_precision.value;
1196 sigma2 = parameters.gp_sigma2.value;
1197 jitter_sigma2 = parameters.jitter_sigma2.value;
1198 report_level = parameters.report_level.value;
1199 linalg::CusolverEighLib::setVerbose(report_level >= 3);
1200 use_alpha_k_predict_mean_ = parameters.use_alpha_k_predict_mean.value;
1201 use_alpha_k_laplace_mean_ = parameters.use_alpha_k_laplace_mean.value;
1202 laplace_skip_scg_threshold_ = parameters.laplace_skip_scg_threshold.value;
1203 use_training_geometry_handle_ =
1204 parameters.use_training_geometry_handle.value;
1205 detail::validateRigidNullDeflationConfiguration(
1206 parameters.use_rigid_null_deflation.value, principled_nugget_);
1207 use_rigid_null_deflation_ = parameters.use_rigid_null_deflation.value;
1208 rigid_deflation_.reset();
1209 rigid_deflation_diag_ = RigidDeflationDiagnostic{};
1210 profile_predict_mean_ = parameters.profile_predict_mean.value;
1211 profile_energy_split_ = parameters.profile_energy_split.value;
1212 profile_gradient_split_ = parameters.profile_gradient_split.value;
1213 log_training_geometry_ = parameters.log_training_geometry.value;
1214 log_rank_block_cholesky_ = false;
1215 if (parameters.log_rank_block_cholesky.value) {
1216 std::fprintf(stderr,
1217 "warning: logRankBlockCholesky is deprecated and "
1218 "ignored; rank-block Cholesky logging was removed\n");
1219 }
1220 scalapack_block_size_ = parameters.scalapack_block_size.value;
1221 scalapack_nprow_ = parameters.scalapack_nprow.value;
1222 cutlass_plugin_path_ = parameters.cutlass_plugin_path.value;
1223 configureDistributedTrainingGrid();
1224 linalg::cutlass::setPluginPath(cutlass_plugin_path_);
1225
1226 if (hyperparameter_mode_override_.has_value()) {
1227 setHyperparameterOptimizationMode(*hyperparameter_mode_override_);
1228 } else {
1229 const auto mode = parameters.optimization_alg.value == "INLA_opt"
1231 : parameters.optimization_alg.value == "MAP_LBFGS_opt"
1234 selectHyperparameterOptimizer(mode);
1235#ifdef USE_CERES
1236 if (parameters.optimization_alg.value == "Ceres_opt")
1237 optimizer_state_->optimizer.emplace<funcmin::Ceres>();
1238#endif
1239 }
1240
1241 // Initialize Gaussian likelihood
1242 prior_parameters.setMu(parameters.prior_mu.value);
1243 prior_parameters.setNu(parameters.prior_nu.value);
1244 prior_parameters.setS2(parameters.prior_s2.value);
1245 lik_gaussian->setSigma2(parameters.sigma2.value);
1246
1247 // Initialize constant covariance function
1248 // Field<double> lengthScale; <----- ? is it calculated or is in initial
1249 // data?
1250
1251 sexpat_cov_func->setMagnSigma2(parameters.magnSigma2.value);
1252 sexpat_cov_func->setConfInfo(this->atoms_config);
1253 auto& length_scales = sexpat_cov_func->getLengthScaleRef();
1254 if (!sexpat_cov_func->usesManifoldChart() &&
1255 length_scales.size() != conf_info.n_pt) {
1256 // The parameter domain follows the pair map even before a fit or
1257 // imported kernel supplies its physical length scales.
1258 length_scales = FieldMatrixd::Ones(1, conf_info.n_pt);
1259 }
1260 sexpat_cov_func->setPriorParametersSqrtt(prior_parameters);
1261 sexpat_cov_func->setPriorParametersGaussian(prior_parameters);
1262 sexpat_cov_func->setPriorParametersLogNormal(prior_parameters);
1263
1264 // Initialize constant covariance function
1265 const_cov_fun->setConstSigma2(parameters.constSigma2.value);
1266
1267 const bool check_derivative = parameters.check_derivative.value == "true";
1268 scg_opt_settings.common.check_derivative = check_derivative;
1269 scg_opt_settings.common.report_level = parameters.report_level.value;
1270 scg_opt_settings.common.max_iter = parameters.max_iter.value;
1271 scg_opt_settings.common.tolerance_func = parameters.tolerance_func.value;
1272 scg_opt_settings.common.tolerance_sol = parameters.tolerance_sol.value;
1273 scg_opt_settings.lambda_limit = parameters.lambda_limit.value;
1274 scg_opt_settings.lambda = parameters.lambda.value;
1275 scg_opt_settings.curvature_mode =
1276 parseScgCurvatureMode(parameters.curvature_mode.value);
1277
1278 ceres_opt_settings.common.check_derivative = check_derivative;
1279 ceres_opt_settings.common.report_level = parameters.report_level.value;
1280 ceres_opt_settings.common.max_iter = parameters.max_iter.value;
1281 ceres_opt_settings.common.tolerance_func = parameters.tolerance_func.value;
1282 ceres_opt_settings.common.tolerance_sol = parameters.tolerance_sol.value;
1283
1285 scg_stalled_ = false;
1286 scg_stall_scope_ = {};
1287 initialized_ = true;
1288 ++laplace_model_revision_;
1289 laplace_posterior_.reset();
1290}
void setHyperparameterOptimizationMode(HyperparameterOptimizationMode mode) noexcept
void forgetRgminSessions() noexcept
void configureLengthScaleTies(const AtomsConfiguration &configuration)
static void setVerbose(bool verbose) noexcept
bool cellIsZero(const double cell[9]) noexcept
Isolated molecule: every entry of the ASE-style 3x3 cell is zero.
Definition MinImage.h:22
void zeroOpenAxes(double cell[9], const std::array< bool, 3 > &periodic) noexcept
Definition MinImage.h:136
bool copyMicLattice(double dest[9], const double src[9]) noexcept
Copy src onto dest only when src is a MIC lattice.
Definition MinImage.h:68
void setPluginPath(std::string path)
Definition CutlassGemm.h:48
void requirePositiveFinitePriorParameter(const char *density, const char *name, double value)
Definition PriorScale.h:17

◆ initialized()

bool gpr::GaussianProcessRegression::initialized ( ) const
inlinenodiscardnoexcept

Definition at line 420 of file GaussianProcessRegression.h.

421 {
422 return initialized_;
423 }

◆ inlaMaxLogMagnSigma2()

double gpr::GaussianProcessRegression::inlaMaxLogMagnSigma2 ( const EigenMatrix & x,
const Eigen::VectorXd & y,
const Eigen::VectorXd & theta_seed ) const
nodiscardprotected

Definition at line 164 of file INLA.cpp.

167{
168 const Eigen::Index columns = x.cols();
169 Eigen::Index energies = columns > 0 ? y.size() / columns : 0;
170 if (!(energies > 0 && energies < y.size() &&
171 energies * columns == y.size()))
172 energies = y.size();
173 const Eigen::Index covariance_parameters =
174 hasTrailingLikelihoodNoiseParameter(theta_seed) ? theta_seed.size() - 1
175 : theta_seed.size();
177 x, energies, y, theta_seed.head(covariance_parameters)));
178}
double mapMaxLogMagnSigma2(double signal_variance) noexcept
double mapRobustSignalVarianceAnchor(const gpr::EigenMatrix &x, Eigen::Index n_e, const Eigen::VectorXd &y, const Eigen::VectorXd &w)

◆ inlaMinimumLengthScale()

double gpr::GaussianProcessRegression::inlaMinimumLengthScale ( double range_x) const
nodiscardprotected

Definition at line 142 of file INLA.cpp.

143{
144 double floor = std::max(1.0e-6, range_x * 1.0e-3);
145 if (!ls_seed_chemical_floor_ || !std::isfinite(floor)) return floor;
146 const priors::CovalentBondPrior bond_prior(atoms_config);
147 const Eigen::VectorXd chemical =
148 bond_prior.lengthScalePerPairtype().cwiseInverse();
149 double covalent = 0.0;
150 for (Eigen::Index k = 0; k < chemical.size(); ++k) {
151 if (!std::isfinite(chemical(k)) || !(chemical(k) > 0.0)) continue;
152 covalent =
153 covalent == 0.0 ? chemical(k) : std::min(covalent, chemical(k));
154 }
155 if (covalent > 0.0) floor = std::max(floor, covalent);
156 return floor;
157}

◆ inlaMinimumLengthScaleForTesting()

double gpr::GaussianProcessRegression::inlaMinimumLengthScaleForTesting ( double range_x) const
inlinenodiscard

Definition at line 3048 of file GaussianProcessRegression.h.

3049 {
3050 return inlaMinimumLengthScale(range_x);
3051 }

◆ installActivePosteriorHessianActionsForTesting()

bool gpr::GaussianProcessRegression::installActivePosteriorHessianActionsForTesting ( MeanHessianPreparation background,
bool background_exact,
MeanHessianPreparation residual,
bool residual_exact )

Replace the active posterior's Hessian actions for one test.

The fitted mean stays in place. A true exact flag makes a false action a refusal of that call only.

Definition at line 135 of file GaussianProcessRegression.cpp.

138{
139 if (!active_posterior_ || !background) return false;
140 auto& hook = optimizer_state_->mean_hessian;
141 hook.active_posterior_actions = true;
142 hook.background = std::move(background);
143 hook.background_exact = background_exact;
144 hook.residual = std::move(residual);
145 hook.residual_exact = residual_exact;
146 return true;
147}

◆ invalidateTrainingFactorCache()

void gpr::GaussianProcessRegression::invalidateTrainingFactorCache ( )

Drop any cached training covariance factor without altering fitted hyperparameters or output normalization, forcing the next conditioning call to build a full Cholesky factor.

Definition at line 253 of file Decompose.cpp.

254{
257 C.resize(0, 0);
260 a.resize(0);
261 b.resize(0);
262 serial_factor_signature_.valid = false;
263#ifdef GPR_LINALG_SCALAPACK
264 auto& distributed_state = backend().distributed();
265 if (distributed_state.cached_L_owned_by(this)) {
266 distributed_state.invalidate_L();
267 }
268 distributed_state.invalidate_inv();
269 training_cholesky_is_distributed_ = false;
270 distributed_factor_signature_.valid = false;
271 parked_training_cholesky_.clear();
272#endif
273}

◆ inverseDiagonalAppendsForTesting()

std::size_t gpr::GaussianProcessRegression::inverseDiagonalAppendsForTesting ( ) const
inlinenodiscardnoexcept

Definition at line 2764 of file GaussianProcessRegression.h.

2765 {
2766 return inverse_diagonal_appends_for_testing_;
2767 }

◆ inverseDiagonalBuildsForTesting()

std::size_t gpr::GaussianProcessRegression::inverseDiagonalBuildsForTesting ( ) const
inlinenodiscardnoexcept

Definition at line 2777 of file GaussianProcessRegression.h.

2778 {
2779 return inverse_diagonal_builds_for_testing_;
2780 }

◆ isDecomposedSuccessfully()

bool gpr::GaussianProcessRegression::isDecomposedSuccessfully ( ) const
inlinenodiscardnoexcept

True after the most recent covariance factorization succeeded. Dest INLA lives in a free helper, so it cannot read the protected flag.

Definition at line 3832 of file GaussianProcessRegression.h.

3833 {
3835 }

◆ isRFFBuilt()

bool gpr::GaussianProcessRegression::isRFFBuilt ( ) const
inlinenodiscardnoexcept

Definition at line 2181 of file GaussianProcessRegression.h.

2182 {
2183 return rff_model_.isBuilt();
2184 }

◆ krylovAddedDiagonal()

std::optional< Eigen::VectorXd > gpr::GaussianProcessRegression::krylovAddedDiagonal ( const EigenMatrix & x)
nodiscardprotected

Definition at line 49 of file KrylovObjective.cpp.

51{
52 if (lik_gaussian == nullptr || sexpat_cov_func == nullptr ||
53 const_cov_fun == nullptr || use_correction_ || use_hssvd_backend_ ||
54 hutch_num_probes_ > 0 || principled_nugget_ ||
55 kernelNuggetCoefficient(x.rows()) != 0.0 ||
56 sexpat_cov_func->usesManifoldChart() ||
57 sexpat_cov_func->usesGeodesicHeatKernel())
58 return std::nullopt;
59 Eigen::VectorXd added =
60 permuteTrainingVector(lik_gaussian->evaluateTrainingVariance(x));
61 if (jitter_sigma2 > 0.0) added.array() += jitter_sigma2;
62 if (added.size() != x.rows() || !(added.array() > 0.0).all() ||
63 !added.allFinite())
64 return std::nullopt;
65 return added;
66}

◆ laplaceMeanBlockPartitionCallsForTesting()

std::size_t gpr::GaussianProcessRegression::laplaceMeanBlockPartitionCallsForTesting ( ) const
inlinenodiscardnoexcept

Definition at line 2685 of file GaussianProcessRegression.h.

2687 {
2688 return laplace_mean_block_partition_calls_for_testing_;
2689 }

◆ laplacePosteriorSignatureBuildsForTesting()

std::size_t gpr::GaussianProcessRegression::laplacePosteriorSignatureBuildsForTesting ( ) const
inlinenodiscardnoexcept

Definition at line 2662 of file GaussianProcessRegression.h.

2664 {
2665 return laplace_posterior_signature_builds_for_testing_;
2666 }

◆ lastAnnealStage()

const AnnealStageSummary & gpr::GaussianProcessRegression::lastAnnealStage ( ) const
inlinenodiscardnoexcept

The last stage that ran, for diagnostics and tests.

Definition at line 2350 of file GaussianProcessRegression.h.

2351 {
2352 return last_anneal_stage_;
2353 }

◆ lastFitConfigurationsForTesting()

std::size_t gpr::GaussianProcessRegression::lastFitConfigurationsForTesting ( ) const
inlinenodiscardnoexcept

Training configurations in the objective of the last hyperparameter fit (the farthest-point subset, or every row after an escalation).

Definition at line 2503 of file GaussianProcessRegression.h.

2504 {
2505 return last_fit_configurations_;
2506 }

◆ lastFitEvaluationsForTesting()

std::size_t gpr::GaussianProcessRegression::lastFitEvaluationsForTesting ( ) const
inlinenodiscardnoexcept

Objective evaluations of the last hyperparameter fit.

Definition at line 2355 of file GaussianProcessRegression.h.

2356 {
2357 return last_fit_evaluations_;
2358 }

◆ lastFitIterations()

int gpr::GaussianProcessRegression::lastFitIterations ( ) const
inlinenodiscardnoexcept

Definition at line 2645 of file GaussianProcessRegression.h.

2646 {
2647 return last_fit_iterations_;
2648 }

◆ lastFitRestarts()

int gpr::GaussianProcessRegression::lastFitRestarts ( ) const
inlinenodiscardnoexcept

Restarts of the last fit; only a marginal-likelihood fit restarts.

Definition at line 2650 of file GaussianProcessRegression.h.

2651 {
2652 return last_fit_restarts_;
2653 }

◆ lastFitStopReason()

const char * gpr::GaussianProcessRegression::lastFitStopReason ( ) const
inlinenodiscardnoexcept

Definition at line 2654 of file GaussianProcessRegression.h.

2655 {
2656 return last_fit_stop_reason_;
2657 }

◆ lastInlaIterations()

std::size_t gpr::GaussianProcessRegression::lastInlaIterations ( ) const
inlinenodiscardnoexcept

Newton (RFO) iterations taken by the most recent INLA mode search.

Definition at line 3033 of file GaussianProcessRegression.h.

3034 {
3035 return last_inla_iterations_;
3036 }

◆ lastObjectiveBackend()

ObjectiveBackend gpr::GaussianProcessRegression::lastObjectiveBackend ( ) const
inlinenodiscardnoexcept

Definition at line 2594 of file GaussianProcessRegression.h.

2595 {
2598 }

◆ lastRefitKind()

int gpr::GaussianProcessRegression::lastRefitKind ( ) const
inlinenodiscardnoexcept

How the last refresh set the hyperparameters: 0 held theta (stationary), 1 took the one Newton step, 2 ran the optimizer.

Definition at line 914 of file GaussianProcessRegression.h.

915 {
916 return last_refit_kind_;
917 }

◆ lastScgFallbackUsedForTesting()

bool gpr::GaussianProcessRegression::lastScgFallbackUsedForTesting ( ) const
inlinenodiscardnoexcept

Definition at line 2628 of file GaussianProcessRegression.h.

2629 {
2630 return last_scg_fallback_used_;
2631 }

◆ lastScgHitIterationBudgetForTesting()

bool gpr::GaussianProcessRegression::lastScgHitIterationBudgetForTesting ( ) const
inlinenodiscardnoexcept

Definition at line 2641 of file GaussianProcessRegression.h.

2642 {
2643 return last_scg_exhausted_iteration_budget_;
2644 }

◆ lastStationarityModel()

int gpr::GaussianProcessRegression::lastStationarityModel ( ) const
inlinenodiscardnoexcept

Definition at line 931 of file GaussianProcessRegression.h.

932 {
933 return last_stationarity_model_;
934 }

◆ lastStationarityShift()

double gpr::GaussianProcessRegression::lastStationarityShift ( ) const
inlinenodiscardnoexcept

Last stationarity decision: predicted shift, its threshold, and which curvature model supplied it (0 none, 1 Laplace, 2 Hessian, 3 inverse Hessian, 4 BB scalar, 5 same-objective gradient probe, 6 exact NLML Hessian-vector product under nlml_hessian_vector).

Definition at line 923 of file GaussianProcessRegression.h.

924 {
925 return last_stationarity_shift_;
926 }

◆ lastStationarityThreshold()

double gpr::GaussianProcessRegression::lastStationarityThreshold ( ) const
inlinenodiscardnoexcept

Definition at line 927 of file GaussianProcessRegression.h.

928 {
929 return last_stationarity_threshold_;
930 }

◆ lastTieScreenCurvatures()

const std::vector< double > & gpr::GaussianProcessRegression::lastTieScreenCurvatures ( ) const
inlinenodiscardnoexcept

Definition at line 1900 of file GaussianProcessRegression.h.

1902 {
1903 return last_tie_screen_curvatures_;
1904 }

◆ lastTieScreenProbes()

int gpr::GaussianProcessRegression::lastTieScreenProbes ( ) const
inlinenodiscardnoexcept

Curvature probes spent by the last length-scale tie screen, whether they were exact NLML Hessian-vector products (nlml_hessian_vector) rather than gradient differences, and the curvature the screen used for each candidate, in candidate order.

Definition at line 1892 of file GaussianProcessRegression.h.

1893 {
1894 return last_tie_screen_probes_;
1895 }

◆ lastTieScreenUsedHessianVector()

bool gpr::GaussianProcessRegression::lastTieScreenUsedHessianVector ( ) const
inlinenodiscardnoexcept

Definition at line 1896 of file GaussianProcessRegression.h.

1897 {
1898 return last_tie_screen_hessian_vector_;
1899 }

◆ lastWarmStartInfeasible()

bool gpr::GaussianProcessRegression::lastWarmStartInfeasible ( ) const
inlinenodiscardnoexcept

True when the last ~optimize~ started from a theta outside the MAP amplitude barrier of the rows it fitted; such a fit cannot move and the caller should re-seed the hyperparameters.

Definition at line 2510 of file GaussianProcessRegression.h.

2511 {
2512 return last_warm_start_infeasible_;
2513 }

◆ leaveOneOutObjectiveEvaluationsForTesting()

std::size_t gpr::GaussianProcessRegression::leaveOneOutObjectiveEvaluationsForTesting ( ) const
inlinenodiscardnoexcept

Definition at line 2942 of file GaussianProcessRegression.h.

2944 {
2945 return leave_one_out_objective_evaluations_for_testing_;
2946 }

◆ leaveOptimizationObjectiveFrame()

void gpr::GaussianProcessRegression::leaveOptimizationObjectiveFrame ( const OptimizationObjectiveFrame & frame,
Eigen::VectorXd * theta )
protectednoexcept

Definition at line 1613 of file Optimize.cpp.

1615{
1616 if (frame.target_scale == 1.0) return;
1617
1618 if (lik_gaussian) {
1619 lik_gaussian->setSigma2(frame.saved_likelihood_sigma2);
1620 }
1621 jitter_sigma2 = frame.saved_jitter_sigma2;
1622 if (frame.has_const_covariance && const_cov_fun) {
1623 const_cov_fun->setConstSigma2(frame.saved_const_sigma2);
1624 }
1625 if (frame.saved_magnitude_prior && sexpat_cov_func) {
1626 sexpat_cov_func->setPriorParametersSqrtt(*frame.saved_magnitude_prior);
1627 }
1628
1629 if (theta != nullptr && theta->size() > 0) {
1630 (*theta)(0) += 2.0 * std::log(frame.target_scale);
1631 // A trailing likelihood-noise entry is a variance in frame units
1632 // and un-scales exactly like the log-magnitude.
1633 if (hasTrailingLikelihoodNoiseParameter(*theta)) {
1634 (*theta)(theta->size() - 1) += 2.0 * std::log(frame.target_scale);
1635 }
1636 }
1637}

◆ lengthScaleFitState()

GaussianProcessRegression::LengthScaleFitState gpr::GaussianProcessRegression::lengthScaleFitState ( ) const
nodiscard

Definition at line 654 of file GaussianProcessRegression.cpp.

655{
657 state.ties = length_scale_ties_;
658 state.enabled = use_length_scale_ties_;
659 return state;
660}

◆ lengthScaleTies()

const LengthScaleTies & gpr::GaussianProcessRegression::lengthScaleTies ( ) const
inlinenodiscardnoexcept

Definition at line 1876 of file GaussianProcessRegression.h.

1877 {
1878 return length_scale_ties_;
1879 }

◆ lengthScaleTiesActive()

bool gpr::GaussianProcessRegression::lengthScaleTiesActive ( Eigen::Index length_count) const
inlinenodiscardnoexcept

Whether the packed parameter vector of length_count log lengths is governed by ties.

Definition at line 1907 of file GaussianProcessRegression.h.

1909 {
1910 return use_length_scale_ties_ && length_scale_ties_.valid &&
1911 length_scale_ties_.count() == length_count;
1912 }

◆ likelihoodNoiseVariance()

double gpr::GaussianProcessRegression::likelihoodNoiseVariance ( ) const
nodiscardnoexcept

Fitted Gaussian likelihood noise variance sigma_n^2. This is the restricted-variance acquisition floor, not the SE signal scale SexpatCF::getMagnSigma2().

Definition at line 486 of file GaussianProcessRegression.cpp.

487{
488 const double lik_noise =
489 lik_gaussian != nullptr ? lik_gaussian->getSigma2() : 0.0;
490 return (lik_noise > 0.0) ? lik_noise
491 : physicalToTrainingNoiseVariance(sigma2);
492}

◆ localLooObjectiveEvaluationsForTesting()

std::size_t gpr::GaussianProcessRegression::localLooObjectiveEvaluationsForTesting ( ) const
inlinenodiscardnoexcept

Definition at line 2951 of file GaussianProcessRegression.h.

2953 {
2954 return local_loo_objective_evaluations_for_testing_;
2955 }

◆ localVariancePrefactor()

virtual double gpr::GaussianProcessRegression::localVariancePrefactor ( const Eigen::VectorXd & ,
const Eigen::VectorXd &  ) const
inlinevirtual

Reimplemented in gpr::StudentTProcessRegression.

Definition at line 3982 of file GaussianProcessRegression.h.

3985 {
3986 return 1.0;
3987 }

◆ localVariancePrefactorFromQuadratic()

virtual double gpr::GaussianProcessRegression::localVariancePrefactorFromQuadratic ( const Eigen::VectorXd & ,
double  ) const
inlinevirtual

Reimplemented in gpr::StudentTProcessRegression.

Definition at line 3988 of file GaussianProcessRegression.h.

3990 {
3991 return 1.0;
3992 }

◆ logProfileSplitSummary()

void gpr::GaussianProcessRegression::logProfileSplitSummary ( )

Definition at line 403 of file GaussianProcessRegression.cpp.

404{
405 if (profile_split_totals_.energy_calls == 0 &&
406 profile_split_totals_.gradient_calls == 0) {
407 return;
408 }
409
410#ifdef GPR_LINALG_SCALAPACK
411 if (!backend().distributed().is_root()) return;
412#endif
413
414 log_man << "GP profile split summary:\n";
415 log_man << " Energy objective: covariance="
416 << profile_split_totals_.energy_covariance_seconds
417 << "s factor=" << profile_split_totals_.energy_factor_seconds
418 << "s posterior=" << profile_split_totals_.energy_posterior_seconds
419 << "s energy_calls=" << profile_split_totals_.energy_calls << "\n";
420 log_man << " Gradient objective: alpha_solve="
421 << profile_split_totals_.gradient_alpha_seconds
422 << "s inverse_cache="
423 << profile_split_totals_.gradient_inverse_seconds
424 << "s const_cf=" << profile_split_totals_.gradient_const_seconds
425 << "s sexpat_cf=" << profile_split_totals_.gradient_sexpat_seconds
426 << "s gradient_calls=" << profile_split_totals_.gradient_calls
427 << "\n";
428}

◆ makeActiveCovarianceOperator()

std::shared_ptr< const KernelOperator > gpr::GaussianProcessRegression::makeActiveCovarianceOperator ( const Eigen::VectorXd & theta,
const std::vector< bool > & active_lengths ) const
nodiscard

Own a fixed pair-kernel snapshot with zero metric weights for inactive lengths. Theta contains log signal variance in physical output units, followed by log descriptor lengths in the full pair-type order.

Definition at line 965 of file ActivePosterior.cpp.

967{
968 if (!sexpat_cov_func || sexpat_cov_func->usesManifoldChart() ||
969 theta.size() != sexpat_cov_func->getLengthScaleRef().size() + 1 ||
970 active_lengths.size() + 1 != static_cast<std::size_t>(theta.size()) ||
971 !theta.allFinite())
972 throw std::invalid_argument("invalid active pair-kernel parameters");
973 for (Eigen::Index i = 0; i < theta.size(); ++i) {
974 if (i > 0 && !active_lengths[static_cast<std::size_t>(i - 1)]) continue;
975 const double value = std::exp(theta(i));
976 if (!(value > 0.0) || !std::isfinite(value))
977 throw std::invalid_argument("invalid active pair-kernel scale");
978 }
979 auto primitive = std::make_shared<SexpatCF>(*sexpat_cov_func);
980 primitive->clearDistanceCache();
981 primitive->setParameters(theta);
982 for (std::size_t i = 0; i < active_lengths.size(); ++i)
983 if (!active_lengths[i])
984 primitive->getLengthScaleRef().data()[i] =
985 std::numeric_limits<double>::infinity();
986 return std::make_shared<Sexpat>(std::move(primitive));
987}

◆ markHyperparametersFitted()

void gpr::GaussianProcessRegression::markHyperparametersFitted ( )
inlinenoexcept

Fitted hyperparameters installed from outside the optimizer, e.g. a seed kernel handed over by the band that produced the training rows.

Definition at line 534 of file GaussianProcessRegression.h.

535 {
536 has_been_optimized_ = true;
537 }

◆ materializeDeviceAlpha()

void gpr::GaussianProcessRegression::materializeDeviceAlpha ( ) const
protected

Definition at line 313 of file DevicePosterior.cpp.

313{ }

◆ materializeDeviceFactor()

void gpr::GaussianProcessRegression::materializeDeviceFactor ( ) const
protected

Definition at line 312 of file DevicePosterior.cpp.

312{ }

◆ measuredRowsAgreeWithPosterior()

GaussianProcessRegression::MeasuredRowVerdict gpr::GaussianProcessRegression::measuredRowsAgreeWithPosterior ( const Observation & rows,
ConvergenceNormType force_norm,
double * max_force_error = nullptr,
double * max_force_sd = nullptr,
double * evidence_nats = nullptr,
double variance_calibration = 1.0,
RefitTrustReport * trust_report = nullptr )

Compare every measured row with the posterior it was drawn against. A row contradicts the posterior when its force error exceeds the posterior force standard deviation at that row (both in the caller's convergence norm): the fitted hyperparameters are then refit. Rows the posterior explains within its own uncertainty leave the hyperparameters in place; conditioning on the rows is what reduces the uncertainty. Unmeasurable when no fitted, decomposed posterior exists or the rows carry no measured forces. ~evidence_nats~, when given, receives the contradiction evidence of the rows: the sum over rows with error e above spread sd of (e/sd)^2/2 - 1/2, in nats. variance_calibration scales the posterior force variance before the comparison: the dimer's own measured calibration of that variance, never below one, so a posterior its trials found overconfident is not contradicted by every row it predicts.

Definition at line 1813 of file Optimize.cpp.

1817{
1818 if (trust_report) trust_report->state_.reset();
1819 std::vector<RefitTrustReport::State::Row> measured_trust;
1820 double worst_error = 0.0, worst_sd = 0.0;
1821 if (max_force_error) *max_force_error = worst_error;
1822 if (max_force_sd) *max_force_sd = worst_sd;
1823 if (evidence_nats) *evidence_nats = 0.0;
1824 if (rows.R.rows() <= 0 || rows.G.rows() != rows.R.rows() ||
1825 rows.G.cols() != rows.R.cols())
1827 // A row contradicts the posterior when the evidence it can add
1828 // exceeds one nat: under the posterior's own Gaussian a residual of
1829 // e against a spread of sd is worth at most (e/sd)^2/2 - 1/2 in log
1830 // likelihood over a model that reproduced it. Any row above one
1831 // spread used to force a refit, so a 1.5-spread row at 3 meV/A
1832 // against 2 meV/A (04_cope's dimer, 21 of 25 fits improving the
1833 // objective by under 0.2 nats) bought a correction fit every phase.
1834 double evidence = 0.0;
1835 for (Eigen::Index row = 0; row < rows.R.rows(); ++row) {
1836 Observation measured;
1837 measured.R = rows.R.middleRows(row, 1);
1838 measured.G = rows.G.middleRows(row, 1);
1839 double row_sd = 0.0, row_error = 0.0;
1840 if (!measureModeRefitTrust(measured, row_sd, row_error, force_norm))
1842 if (trust_report) measured_trust.push_back({row_sd, row_error});
1843 // The spread the row is judged against is the one the caller has
1844 // measured for this posterior: the reported variance times its
1845 // trial calibration.
1846 if (std::isfinite(variance_calibration) && variance_calibration > 1.0)
1847 row_sd *= std::sqrt(variance_calibration);
1848 worst_error = std::max(worst_error, row_error);
1849 worst_sd = std::max(worst_sd, row_sd);
1850 if (row_error > row_sd) {
1851 const double ratio = row_sd > 0.0
1852 ? row_error / row_sd
1853 : std::numeric_limits<double>::infinity();
1854 evidence += std::isfinite(ratio)
1855 ? 0.5 * (ratio * ratio - 1.0)
1856 : std::numeric_limits<double>::infinity();
1857 }
1858 }
1859 if (trust_report)
1860 trust_report->state_ = std::make_shared<RefitTrustReport::State>(
1861 *this, rows, force_norm, std::move(measured_trust));
1862 if (max_force_error) *max_force_error = worst_error;
1863 if (max_force_sd) *max_force_sd = worst_sd;
1864 if (evidence_nats) *evidence_nats = evidence;
1865 if (evidence >= 1.0) {
1866 // Rows the posterior cannot explain move the marginal likelihood by
1867 // more than their expected log predictive density: the next fit
1868 // may land in another basin, and the previous fit's curvature
1869 // record would steer it. The fit opens cold.
1872 }
1874}

◆ monitorAndAdaptHyperparameters()

bool gpr::GaussianProcessRegression::monitorAndAdaptHyperparameters ( const Eigen::VectorXd & new_parameters)
protected

Monitors hyperparameter history for oscillations and adapts the FPS history size.

If the ratio of sign flips in the recent history of hyperparameter updates exceeds a threshold, it indicates instability. In response, the size of the data subset for future optimizations is increased.

Parameters
new_parametersThe latest vector of optimized hyperparameters.
Returns
bool Returns 'true' if the history size was increased (signaling a need to retry), 'false' otherwise.

Definition at line 3521 of file Optimize.cpp.

3523{
3524 // 1. Store the latest hyperparameter vector and maintain history buffer
3525 // size.
3526 hyperparameter_history_.push_back(new_parameters);
3527 while (static_cast<int>(hyperparameter_history_.size()) >
3528 monitoring_window_ + 1) {
3529 hyperparameter_history_.pop_front();
3530 }
3531
3532 // 2. Check for instability only if we have enough data and history is not
3533 // maxed out.
3534 if (static_cast<int>(hyperparameter_history_.size()) !=
3535 monitoring_window_ + 1 ||
3536 fps_options.history >= max_history_) {
3537 return false; // Not enough data or already maxed out, so no retry.
3538 }
3539
3540 const int num_params = new_parameters.size();
3541 // A tied member mirrors its leader; only the fitted parameters count.
3542 const auto counted = [&](int j) {
3543 const auto& ties = length_scale_ties_;
3544 if (!ties.valid || j < 1 || j > static_cast<int>(ties.count()))
3545 return true;
3546 const auto t = static_cast<std::size_t>(j - 1);
3547 return ties.leader[t] == static_cast<Index_t>(t);
3548 };
3549 int counted_params = 0;
3550 for (int j = 0; j < num_params; ++j)
3551 if (counted(j)) ++counted_params;
3552 const int total_possible_flips = counted_params * (monitoring_window_ - 1);
3553 if (total_possible_flips <= 0) {
3554 return false; // Cannot compute flips, so no retry.
3555 }
3556
3557 int sign_flips = 0;
3558 // Iterate through a 3-point sliding window to check for oscillations.
3559 for (int i = 0; i < monitoring_window_ - 1; ++i) {
3560 const Eigen::VectorXd& h_old = hyperparameter_history_[i];
3561 const Eigen::VectorXd& h_mid = hyperparameter_history_[i + 1];
3562 const Eigen::VectorXd& h_new = hyperparameter_history_[i + 2];
3563
3564 Eigen::VectorXd delta1 = h_mid - h_old;
3565 Eigen::VectorXd delta2 = h_new - h_mid;
3566
3567 // Check for sign flips for each hyperparameter component
3568 for (int j = 0; j < num_params; ++j) {
3569 if (!counted(j)) continue;
3570 if (delta1(j) * delta2(j) < -1e-9) { // Using a small tolerance
3571 sign_flips++;
3572 }
3573 }
3574 }
3575
3576 // 3. If instability is detected, increase the history size and signal for a
3577 // retry.
3578 double flip_ratio = static_cast<double>(sign_flips) / total_possible_flips;
3579 if (flip_ratio > flip_threshold_) {
3580 if (report_level >= 1) {
3581 log_man << "Hyperparameter instability detected! Flip ratio: "
3582 << flip_ratio << " > " << flip_threshold_ << "\n";
3583 }
3584
3585 int old_history = fps_options.history;
3586 // A history already at or beyond the cap (the full-set setting is
3587 // INT_MAX) stays: old_history + increment would overflow.
3588 if (old_history < max_history_) {
3589 fps_options.history =
3590 std::min(old_history + history_increment_, max_history_);
3591 }
3592
3593 if (report_level >= 1) {
3594 log_man << "Increasing FPS history size from " << old_history
3595 << " to " << fps_options.history << "\n";
3596 }
3597
3598 // Clear history after adjustment to start fresh monitoring on the next
3599 // attempt.
3601 return true; // Signal to retry
3602 }
3603
3604 // No instability detected, no retry needed.
3605 return false;
3606}
std::deque< Eigen::VectorXd > hyperparameter_history_

◆ mpiContext()

linalg::MpiContext gpr::GaussianProcessRegression::mpiContext ( ) const
inlinenodiscard

Definition at line 400 of file GaussianProcessRegression.h.

401 {
402 return backend().mpi();
403 }

◆ nlmlHessianVectorCurvatureRequested()

bool gpr::GaussianProcessRegression::nlmlHessianVectorCurvatureRequested ( ) const
inlinenodiscardnoexcept

True when curvature_mode is nlml_hessian_vector. SCG curvature, the length-scale tie screen and the stationarity check then take their curvature from evaluateNlmlHessianVector. Where the product is not available or fails, each takes the finite_difference path instead: SCG's gradient probe, the tie screen's gradient differences and the stationarity check's gradient secant.

Definition at line 2420 of file GaussianProcessRegression.h.

2421 {
2422 return scg_opt_settings.curvature_mode ==
2424 }

◆ nlmlHessianVectorFallbacks()

int gpr::GaussianProcessRegression::nlmlHessianVectorFallbacks ( ) const
inlinenodiscardnoexcept

Times this model routed an nlml_hessian_vector request to the finite_difference path (a fit of an objective without the product, a tie screen or a stationarity check), each logged at report level 1.

Definition at line 2428 of file GaussianProcessRegression.h.

2429 {
2430 return nlml_hessian_vector_fallbacks_;
2431 }

◆ nonfiniteMarginalLikelihoodRejections()

std::size_t gpr::GaussianProcessRegression::nonfiniteMarginalLikelihoodRejections ( ) const
nodiscardnoexcept

Lifetime count of refits that kept the input theta because the marginal likelihood there was non-finite. The stop reason names the same event.

Definition at line 5133 of file Optimize.cpp.

5135{
5136 return optimizer_state_->nonfinite_marginal_likelihood_rejections;
5137}

◆ noteNlmlHessianVectorFallback()

void gpr::GaussianProcessRegression::noteNlmlHessianVectorFallback ( const char * where,
const char * why )

Counts and logs one such routing: where took the finite_difference path because of why.

Definition at line 361 of file Hessian.cpp.

363{
364 ++nlml_hessian_vector_fallbacks_;
365 if (report_level >= 1) {
366 log_man << "curvature_mode nlml_hessian_vector: " << why << "; "
367 << where << " takes the finite_difference path.\n";
368 }
369}

◆ noteSurrogateContradiction()

void gpr::GaussianProcessRegression::noteSurrogateContradiction ( )
inlinenoexcept

Evidence against the surrogate at a measured point, the trigger of the next anneal stage under the evidence policy.

Definition at line 2327 of file GaussianProcessRegression.h.

2328 {
2329 surrogate_contradicted_ = true;
2330 }

◆ objectiveParameterStamp()

Eigen::VectorXd gpr::GaussianProcessRegression::objectiveParameterStamp ( ) const
nodiscardprotected

Kernel, constant and likelihood parameters the objective was evaluated at, to tie a gradient call to it.

Definition at line 34 of file KrylovObjective.cpp.

35{
36 const Eigen::VectorXd kernel = sexpat_cov_func != nullptr
37 ? sexpat_cov_func->combineParameters()
38 : Eigen::VectorXd();
39 Eigen::VectorXd stamp(kernel.size() + 3);
40 stamp.head(kernel.size()) = kernel;
41 stamp(kernel.size()) =
42 const_cov_fun != nullptr ? const_cov_fun->getConstSigma2() : 0.0;
43 stamp(kernel.size() + 1) =
44 lik_gaussian != nullptr ? lik_gaussian->getSigma2() : 0.0;
45 stamp(kernel.size() + 2) = jitter_sigma2;
46 return stamp;
47}

◆ objectivePlan()

ObjectivePlan gpr::GaussianProcessRegression::objectivePlan ( ) const
inlinenodiscardnoexcept

Definition at line 2608 of file GaussianProcessRegression.h.

2609 {
2610 return krylov_objective_.plan;
2611 }

◆ objectiveStationaritySkipMayBeActive()

bool gpr::GaussianProcessRegression::objectiveStationaritySkipMayBeActive ( ) const
inlinenodiscardnoexcept

Definition at line 1450 of file GaussianProcessRegression.h.

1451 {
1452 return objective_stationarity_skip_auto_ ||
1453 (laplace_skip_scg_threshold_ > 0.0 &&
1454 std::isfinite(laplace_skip_scg_threshold_));
1455 }

◆ objectiveStationaritySkipThresholdForTesting()

double gpr::GaussianProcessRegression::objectiveStationaritySkipThresholdForTesting ( const Eigen::VectorXd & theta_reference) const
inlinenodiscardnoexcept

Definition at line 1461 of file GaussianProcessRegression.h.

1463 {
1464 return objectiveStationaritySkipThreshold(theta_reference);
1465 }

◆ observationBandInfluence() [1/2]

bool gpr::GaussianProcessRegression::observationBandInfluence ( const Observation & observation,
const Coord & band_positions,
Eigen::VectorXd & influence,
bool collective,
const std::vector< char > & protected_rows,
Eigen::VectorXd * removal_norm = nullptr )
nodiscard

Nonzero entries of protected_rows exclude observations from scoring and give them infinite influence. A collective call excludes a row only when every process protects it. An empty mask scores every row.

removal_norm, when supplied, receives for every scored observation J the kernel norm of the change its removal makes to the posterior mean, sqrt(alpha_J^T (P_JJ)^{-1} alpha_J) with P = C^{-1}. The reproducing property bounds the change at every geometry x by sqrt(k(x, x)) times that norm, on the band and away from it.

Definition at line 4547 of file Optimize.cpp.

4551{
4552 // Exact block downdate (scripts/derive_adaptive_pruning_influence.py):
4553 // removing observation j shifts the posterior mean at query x* by
4554 // k(x*,X) P E_j (E_j^T P E_j)^{-1} E_j^T alpha, P = C^{-1},
4555 // whose first factor is the block leave-one-out residual and whose
4556 // second is the smoother's reliance on j at x*.
4557 //
4558 // The mean is not the whole story. Removing a row also widens the
4559 // posterior at x*, by the quadratic form
4560 // w_j^T (E_j^T P E_j)^{-1} w_j, w_j = (k(x*,X) P) E_j,
4561 // which is non-negative because the middle factor is a diagonal
4562 // block of a positive definite inverse: dropping data never
4563 // sharpens a belief. Acquisition reads that variance, so a row can
4564 // leave the predicted energy untouched and still move where the
4565 // search looks next. Scoring the mean alone lets such a row be
4566 // dropped as inert and then changes the acquisition sequence, which
4567 // is the opposite of inert.
4568 //
4569 // Reported per observation as the worst over the band's energy
4570 // channel and every Cartesian force channel of the mean shift and
4571 // the standard-deviation inflation, both in the model's own target
4572 // units so one noise-sigma gate covers both. A row that leaves the
4573 // energy profile untouched can still move a force the search reads.
4574 const Eigen::Index n_obs = observation.R.rows();
4575 const Eigen::Index dim = observation.R.cols();
4576 if (n_obs == 0 || dim == 0 || band_positions.rows() == 0 ||
4577 band_positions.cols() != dim || observation.E.size() != n_obs ||
4578 observation.G.rows() != n_obs || observation.G.cols() != dim ||
4579 (!protected_rows.empty() &&
4580 protected_rows.size() != static_cast<std::size_t>(n_obs))) {
4581 return false;
4582 }
4583 const Eigen::Index block = dim + 1;
4584 Eigen::VectorXi excluded = Eigen::VectorXi::Zero(n_obs);
4585 for (std::size_t row = 0; row < protected_rows.size(); ++row)
4586 excluded(static_cast<Eigen::Index>(row)) = protected_rows[row] != 0;
4587
4588 aux::AuxiliaryFunctionality aux_func;
4589 EigenMatrix x;
4590 Eigen::VectorXd x_ind;
4591 aux_func.assembleMatrixOfRepetitiveCoordinates(observation.R, x, x_ind);
4592 Eigen::VectorXd y;
4593 aux_func.assembleVectorFromEnergyAndGradient(observation, y);
4594 subtractPriorMeanFromTargets(observation.R, observation.E.size(), y);
4595 // No standardizeTargets: the classic profile runs normalization-free,
4596 // so raw targets already are the frame the likelihood noise lives in
4597 // and the caller compares influences against that noise directly.
4598
4599 const Eigen::Index order = y.size();
4600 // A count-dependent nugget prevents appending to a factor, but a factor
4601 // at this exact order already contains the required regularization.
4602 bool reuse_factor = !use_hssvd_backend_ && !active_posterior_ &&
4603 !use_correction_ && sexpat_cov_func != nullptr &&
4604 lik_gaussian != nullptr &&
4605 !sexpat_cov_func->usesManifoldChart() &&
4606 !sexpat_cov_func->usesGeodesicHeatKernel() &&
4608 if (reuse_factor) {
4609 const EigenMatrix ordered_rows = permuteTrainingRows(x);
4610#ifdef GPR_LINALG_KOKKOS
4611 if (hasDevicePosterior()) {
4612 const auto& lengths = sexpat_cov_func->getLengthScaleRef();
4613 reuse_factor = device_posterior_->matchesTraining(
4614 ordered_rows, permuteTrainingVector(x_ind),
4615 lik_gaussian->evaluateTrainingVariance(ordered_rows),
4616 Eigen::Map<const Eigen::VectorXd>(lengths.data(),
4617 lengths.size()),
4618 sexpat_cov_func->getMagnSigma2(),
4619 const_cov_fun->getConstSigma2(), kernelNuggetCoefficient(order),
4620 jitter_sigma2);
4621 } else {
4622#endif
4623#ifdef GPR_LINALG_SCALAPACK
4624 const auto& signature = distributed_factor_signature_;
4625 reuse_factor =
4626 collective && signature.jitter == 0.0 &&
4627 signature.configured_jitter == jitter_sigma2 &&
4628 detail::sameSexpatGeometry(signature.kernel_configuration,
4629 sexpat_cov_func->getConfInfo(),
4630 signature.far_field_radius,
4631 sexpat_cov_func->farFieldRadius());
4632#else
4633 const auto& signature = serial_factor_signature_;
4634 reuse_factor =
4635 signature.valid && signature.indices.size() == x_ind.size() &&
4636 signature.jitter_sigma2 == jitter_sigma2 &&
4637 !signature.manifold_chart && !signature.geodesic_heat &&
4638 signature.indices == permuteTrainingVector(x_ind) &&
4639 detail::sameSexpatGeometry(
4640 signature.kernel_geometry, sexpat_cov_func->getConfInfo(),
4641 signature.far_field_radius, sexpat_cov_func->farFieldRadius());
4642#endif
4643 reuse_factor =
4644 reuse_factor && signature.valid &&
4645 signature.nugget_coefficient ==
4646 kernelNuggetCoefficient(order) &&
4647 signature.theta == sexpat_cov_func->combineParameters() &&
4648 signature.rows.rows() == order &&
4649 signature.rows.cols() == ordered_rows.cols() &&
4650 signature.rows == ordered_rows;
4651 if (reuse_factor) {
4652 const Eigen::VectorXd noise = permuteTrainingVector(
4653 lik_gaussian->evaluateTrainingVariance(x));
4654 const Eigen::VectorXd constant =
4655 permuteTrainingVector(detail::constantCovarianceUpdate(
4656 const_cov_fun.get(), x_ind));
4657 reuse_factor =
4658 noise == signature.noise && constant == signature.constant;
4659 }
4660#ifdef GPR_LINALG_KOKKOS
4661 }
4662#endif
4663 }
4664#ifdef GPR_LINALG_SCALAPACK
4665 if (collective) {
4666 const auto context = backend().mpi();
4667 int reusable = reuse_factor ? 1 : 0;
4668 if (context.is_distributed())
4669 MPI_Allreduce(MPI_IN_PLACE, &reusable, 1, MPI_INT, MPI_MIN,
4670 context.comm);
4671 if (context.is_distributed())
4672 MPI_Allreduce(MPI_IN_PLACE, excluded.data(),
4673 static_cast<int>(n_obs), MPI_INT, MPI_MIN,
4674 context.comm);
4675 reuse_factor = reusable != 0;
4676 }
4677#else
4678 (void)collective;
4679#endif
4680 // The local factor is taken in observation-major order, so that the
4681 // rows of geometry j are the contiguous block [j b, (j + 1) b),
4682 // b = dim + 1. With C' = Q C Q^T = L' L'^T the precision block is
4683 // E_j^T C^-1 E_j = V_j^T V_j, L'[s:, s:] V_j = [I_b; 0], s = j b,
4684 // because L'^-1 e_c vanishes above row c. Each block then costs a
4685 // solve on the trailing (order - s) rows instead of all of them, and
4686 // the blocks together cost order^3 / 3 rather than order^3.
4687 // (scripts/derive_band_influence_trailing_blocks.py checks the identity.)
4688 EigenMatrix local_lower;
4689 Eigen::PermutationMatrix<Eigen::Dynamic, Eigen::Dynamic, int>
4690 observation_major;
4691 // A collective call shares the covariance blocks out across the ranks;
4692 // the disjoint exact sum returns the single-rank matrix to every rank.
4693 bool collective_assembly = false;
4694#ifdef GPR_LINALG_SCALAPACK
4695 collective_assembly = collective && backend().mpi().is_distributed();
4696#endif
4697 if (!reuse_factor) {
4698 if (order != n_obs * block) return false;
4699 EigenMatrix covariance;
4701 x, x_ind, covariance, /*serial_per_rank=*/!collective_assembly);
4702 if (covariance.rows() != order) return false;
4703 // Channel-major row j + b n_obs is observation-major row j b + b.
4704 observation_major.resize(order);
4705 for (Eigen::Index j = 0; j < n_obs; ++j)
4706 for (Eigen::Index b = 0; b < block; ++b)
4707 observation_major.indices()(j + b * n_obs) =
4708 static_cast<int>(j * block + b);
4709 // Q C Q^T, lower triangle only (the factorization and every solve
4710 // read no other entry). Each target column gathers contiguous
4711 // channel segments of one source column.
4712 local_lower = EigenMatrix::Zero(order, order);
4713 for (Eigen::Index j = 0; j < n_obs; ++j) {
4714 for (Eigen::Index b = 0; b < block; ++b) {
4715 const Eigen::Index target = j * block + b;
4716 const double* source = covariance.col(j + b * n_obs).data();
4717 double* column = local_lower.col(target).data();
4718 for (Eigen::Index channel = 0; channel < block; ++channel) {
4719 const double* segment = source + channel * n_obs;
4720 // Rows j' block + channel at or below the diagonal.
4721 const Eigen::Index first =
4722 target > channel
4723 ? (target - channel + block - 1) / block
4724 : 0;
4725 for (Eigen::Index row = first; row < n_obs; ++row)
4726 column[row * block + channel] = segment[row];
4727 }
4728 }
4729 }
4730 covariance.resize(0, 0);
4731 if (jitter_sigma2 > 0.0)
4732 local_lower.diagonal().array() += jitter_sigma2;
4733 const Eigen::LLT<Eigen::Ref<EigenMatrix>> factor(local_lower);
4734 if (factor.info() != Eigen::Success) return false;
4735 } else {
4736 ++band_influence_factor_reuses_for_testing_;
4737 }
4738 influence = Eigen::VectorXd::Constant(
4739 n_obs, std::numeric_limits<double>::infinity());
4740 if (removal_norm != nullptr) *removal_norm = influence;
4741 if (excluded.minCoeff() != 0) return true;
4742 const auto whiten = [&](EigenMatrix rhs) -> EigenMatrix {
4743 if (reuse_factor) {
4744 EigenMatrix rhs_perm = permuteTrainingRows(rhs);
4745 if (rigid_deflation_.isActiveForFullOrder(rhs_perm.rows()))
4746 rhs_perm = rigid_deflation_.projectRows(rhs_perm);
4747 return trainingSolver().whitenColumns(rhs_perm);
4748 }
4749 rhs = observation_major * rhs;
4750 local_lower.template triangularView<Eigen::Lower>().solveInPlace(rhs);
4751 return rhs;
4752 };
4753 const auto solve = [&](const EigenMatrix& rhs) -> EigenMatrix {
4754 if (reuse_factor && rigid_deflation_.isActiveForFullOrder(rhs.rows())) {
4755 EigenMatrix rhs_perm = permuteTrainingRows(rhs);
4756 EigenMatrix rhs_proj = rigid_deflation_.projectRows(rhs_perm);
4757 EigenMatrix solved_r = trainingSolver().solveColumns(rhs_proj);
4758 EigenMatrix result =
4759 rigid_deflation_.liftSolvedColumns(rhs_perm, solved_r);
4761 result =
4763 return result;
4764 }
4765 EigenMatrix result = whiten(rhs);
4766 if (reuse_factor) {
4767 result = trainingSolver().unwhitenColumns(result);
4769 result =
4771 } else {
4772 local_lower.transpose()
4773 .template triangularView<Eigen::Upper>()
4774 .solveInPlace(result);
4775 result = observation_major.transpose() * result;
4776 }
4777 return result;
4778 };
4779 const Eigen::VectorXd alpha = solve(y);
4780
4781 // Band queries on the energy channel and every Cartesian force
4782 // channel. Channel 0 is the energy; channel c = 1..dim is the
4783 // derivative along Cartesian coordinate c - 1, the same trailing
4784 // column assembleMatrixOfRepetitiveCoordinates writes.
4785 const Eigen::Index n_band = band_positions.rows();
4786 const Eigen::Index n_queries = n_band * block;
4787 EigenMatrix xq(n_queries, dim + 1);
4788 Eigen::VectorXd xq_ind(n_queries);
4789 for (Eigen::Index channel = 0; channel < block; ++channel) {
4790 const Eigen::Index row0 = channel * n_band;
4791 xq.middleRows(row0, n_band).leftCols(dim) = band_positions;
4792 xq.middleRows(row0, n_band)
4793 .col(dim)
4794 .setConstant(static_cast<double>(channel));
4795 xq_ind.segment(row0, n_band).setConstant(static_cast<double>(channel));
4796 }
4797 EigenMatrix K_qt;
4798 evaluateCovarianceMatrix(xq, x, xq_ind, x_ind, K_qt,
4799 /*serial_per_rank=*/true);
4800 if (K_qt.rows() != n_queries || K_qt.cols() != order) return false;
4801
4802 const EigenMatrix W = solve(K_qt.transpose()).transpose();
4803 // Only one geometry's precision block is needed at a time:
4804 // E_j^T C^-1 E_j = (L^-1 E_j)^T (L^-1 E_j). Streaming these
4805 // right-hand sides bounds scratch storage by order * (dim + 1).
4806 EigenMatrix columns;
4807 if (reuse_factor) columns = EigenMatrix::Zero(order, block);
4808
4809 // The local factor is replicated, so the geometries can be shared out:
4810 // each one's precision block, and everything derived from it, is
4811 // computed whole by a single rank, and a minimum against +inf on the
4812 // others hands the values back unchanged. The distributed factor's
4813 // solves are collective and stay on every rank.
4814 int owner_rank = 0, owners = 1;
4815#ifdef GPR_LINALG_SCALAPACK
4816 const bool share_geometries = !reuse_factor && collective_assembly;
4817 if (share_geometries) {
4818 owner_rank = backend().mpi().rank;
4819 owners = backend().mpi().nprocs;
4820 }
4821#endif
4822
4823 Eigen::VectorXi idx(block);
4824 EigenMatrix gram(block, block);
4825 Eigen::VectorXd alpha_block(block);
4826 for (Eigen::Index j = 0; j < n_obs; ++j) {
4827 if (excluded(j)) continue;
4828 if (j % owners != owner_rank) continue;
4829 for (Eigen::Index b = 0; b < block; ++b)
4830 idx(b) = static_cast<int>(j + b * n_obs);
4831 for (Eigen::Index r = 0; r < block; ++r)
4832 alpha_block(r) = alpha(idx(r));
4833 EigenMatrix block_whitened;
4834 if (reuse_factor) {
4835 columns.setZero();
4836 for (Eigen::Index r = 0; r < block; ++r)
4837 columns(idx(r), r) = 1.0;
4838 block_whitened = whiten(columns);
4839 } else {
4840 const Eigen::Index first = j * block;
4841 const Eigen::Index trailing = order - first;
4842 block_whitened = EigenMatrix::Zero(trailing, block);
4843 block_whitened.topRows(block).setIdentity();
4844 local_lower.bottomRightCorner(trailing, trailing)
4845 .template triangularView<Eigen::Lower>()
4846 .solveInPlace(block_whitened);
4847 }
4848 gram.noalias() = block_whitened.transpose() * block_whitened;
4849 if (reuse_factor && rigid_deflation_.isActiveForFullOrder(order)) {
4850 const EigenMatrix cols_perm = permuteTrainingRows(columns);
4851 for (Eigen::Index i = 0; i < rigid_deflation_.num_geometries; ++i) {
4852 const auto& blk =
4853 rigid_deflation_.blocks[static_cast<std::size_t>(i)];
4854 if (blk.rigid_modes <= 0) continue;
4855 const auto g_block = cols_perm.middleRows(
4856 blk.full_row_offset + 1, blk.full_grad_dim);
4857 if (g_block.isZero(0.0)) continue;
4858 const EigenMatrix r_proj = blk.R.transpose() * g_block;
4859 gram.noalias() += (1.0 / blk.grad_noise_variance) *
4860 (r_proj.transpose() * r_proj);
4861 }
4862 }
4863 const Eigen::LDLT<EigenMatrix> gram_solver(gram);
4864 if (gram_solver.info() != Eigen::Success) {
4865 // Undecidable: never prune on a failed downdate.
4866 influence(j) = std::numeric_limits<double>::infinity();
4867 continue;
4868 }
4869 const Eigen::VectorXd u = gram_solver.solve(alpha_block);
4870 if (removal_norm != nullptr) {
4871 // mu - mu_{-J} = k(., X) P E_J u has squared kernel norm
4872 // u^T (E_J^T P E_J) u = alpha_J^T u.
4873 const double squared = alpha_block.dot(u);
4874 if (std::isfinite(squared))
4875 (*removal_norm)(j) = std::sqrt(std::max(squared, 0.0));
4876 }
4877 double worst = 0.0;
4878 Eigen::VectorXd w_j(block);
4879 for (Eigen::Index i = 0; i < n_queries; ++i) {
4880 double shift = 0.0;
4881 for (Eigen::Index r = 0; r < block; ++r) {
4882 w_j(r) = W(i, idx(r));
4883 shift += w_j(r) * u(r);
4884 }
4885 worst = std::max(worst, std::abs(shift));
4886 // Variance inflation at this band point, as a standard
4887 // deviation so it shares the noise-sigma yardstick with the
4888 // mean shift. The form is non-negative by construction; a
4889 // negative value is a broken factorization, not a sharper
4890 // posterior, so it is treated as undecidable.
4891 const double var_gain = w_j.dot(gram_solver.solve(w_j));
4892 if (!std::isfinite(var_gain)) {
4893 worst = std::numeric_limits<double>::infinity();
4894 break;
4895 }
4896 if (var_gain > 0.0) {
4897 worst = std::max(worst, std::sqrt(var_gain));
4898 }
4899 }
4900 influence(j) = std::isfinite(worst)
4901 ? worst
4902 : std::numeric_limits<double>::infinity();
4903 }
4904#ifdef GPR_LINALG_SCALAPACK
4905 if (share_geometries) {
4906 const auto context = backend().mpi();
4907 MPI_Allreduce(MPI_IN_PLACE, influence.data(), static_cast<int>(n_obs),
4908 MPI_DOUBLE, MPI_MIN, context.comm);
4909 if (removal_norm != nullptr)
4910 MPI_Allreduce(MPI_IN_PLACE, removal_norm->data(),
4911 static_cast<int>(n_obs), MPI_DOUBLE, MPI_MIN,
4912 context.comm);
4913 }
4914#endif
4915 return true;
4916}
EigenMatrix unwhitenColumns(const EigenMatrix &B) const
bool is_distributed() const noexcept
Definition MpiContext.h:67

◆ observationBandInfluence() [2/2]

bool gpr::GaussianProcessRegression::observationBandInfluence ( const Observation & observation,
const Coord & band_positions,
Eigen::VectorXd & influence,
bool collective = false )
nodiscard

Per-observation influence on the band posterior.

Fills influence with, for each row of observation, the largest shift its removal would produce in the posterior energy or a Cartesian force at any point of band_positions, computed exactly by the block downdate identity (derivation and verification in scripts/derive_adaptive_pruning_influence.py). Values are in the model's target units, so a caller prunes by comparing against the likelihood noise. Returns false when the model cannot be factored, in which case nothing may be pruned. With collective=true, every process in the model's group participates in factor reuse; a call that cannot reuse the training factor shares the covariance blocks and the scored observations out across the processes, and every process receives the values of a rank-local call.

Definition at line 4539 of file Optimize.cpp.

4542{
4543 return observationBandInfluence(observation, band_positions, influence,
4544 collective, {});
4545}
bool observationBandInfluence(const Observation &observation, const Coord &band_positions, Eigen::VectorXd &influence, bool collective=false)
Per-observation influence on the band posterior.

◆ optimize()

void gpr::GaussianProcessRegression::optimize ( const Observation & observation)

Optimize paramaters of a Gaussian process.

This function optimizes the parameters of a GP structure given matrix X of training inputs and vector Y of training targets.

Definition at line 550 of file Optimize.cpp.

551{
552 const auto optimize_start = std::chrono::steady_clock::now();
553 const double solve0 = linalg::teamSolveWallSeconds();
554 const double factor0 = linalg::teamFactorWallSeconds();
555 const double eigen0 = PhaseTimers::eigensolve_seconds;
556 const double kernel0 = PhaseTimers::assembly_seconds;
557 const double gradient0 = PhaseTimers::gradient_seconds;
558 const double curvature0 = PhaseTimers::curvature_seconds;
559 const double energy0 = PhaseTimers::energy_seconds;
560 const double subset0 = PhaseTimers::subset_seconds;
561 const double cache0 = PhaseTimers::cache_seconds;
562 const double descriptor0 = PhaseTimers::descriptor_seconds;
563 const double posterior0 = PhaseTimers::posterior_seconds;
564 struct ExclusiveOptimize {
565 std::chrono::steady_clock::time_point start;
566 double solve0, factor0, eigen0, kernel0, gradient0, curvature0, energy0,
567 subset0, cache0, descriptor0, posterior0;
568 ~ExclusiveOptimize()
569 {
570 const double wall = std::chrono::duration<double>(
571 std::chrono::steady_clock::now() - start)
572 .count();
573 const double nested =
574 (linalg::teamSolveWallSeconds() - solve0) +
575 (linalg::teamFactorWallSeconds() - factor0) +
576 (PhaseTimers::eigensolve_seconds - eigen0) +
577 (PhaseTimers::assembly_seconds - kernel0) +
578 (PhaseTimers::gradient_seconds - gradient0) +
579 (PhaseTimers::curvature_seconds - curvature0) +
580 (PhaseTimers::energy_seconds - energy0) +
581 (PhaseTimers::subset_seconds - subset0) +
582 (PhaseTimers::cache_seconds - cache0) +
583 (PhaseTimers::descriptor_seconds - descriptor0) +
584 (PhaseTimers::posterior_seconds - posterior0);
585 PhaseTimers::schedule_seconds += std::max(0.0, wall - nested);
586 }
587 } exclusive_optimize{optimize_start, solve0, factor0, eigen0,
588 kernel0, gradient0, curvature0, energy0,
589 subset0, cache0, descriptor0, posterior0};
590 detail::requireJointTrainingObservation(
591 observation, "GaussianProcessRegression::optimize");
592 if (wallClockLimitReached()) {
593 failedOptimizer = true;
594 last_fit_stop_reason_ = "wall-clock limit";
595 return;
596 }
597 if (atomic_environment_model_) {
599 fitAtomicEnvironmentModel(observation, true);
600 return;
601 }
602 fitted_hyperparameter_density_.reset();
604 const bool select_components = hasPendingResidualModelRefit();
605 const auto active =
606 select_components
607 ? std::vector<bool>(sexpat_cov_func->getLengthScaleRef().size(),
608 true)
609 : active_refit_lengths_;
610 const bool skipped_setup = active_refit_setup_skipped_;
612 const bool fitted = fitActivePosteriorImpl(
613 observation, active, select_components, select_components);
614 // An independent, anchor-conditioned residual expands the retained
615 // posterior even when both components use the pair primitive. The
616 // fitted candidate evidence determines which correction is retained.
617 if (fitted) {
618 has_been_optimized_ = true;
619 return;
620 }
621 active_posterior_.reset();
622 mode_refit_policy_.reset();
623 if (skipped_setup)
624 setHyperparameters(observation, atoms_config, false, false, false);
625 if (report_level >= 1)
626 log_man << "Active correction did not converge; refitting all GP "
627 "hyperparameters.\n";
628 }
629 active_posterior_.reset();
630 if (has_been_optimized_ && scg_opt_settings.active_parameters.empty()) {
631 // A full refit releases the seed's identifiability mask. Active
632 // refits carry an explicit mask or an anchor-conditioned residual;
633 // a changed target must not remain confined to the seed's amplitude.
634 scg_opt_settings.active_parameters =
635 fullRefitMask(sexpat_cov_func.get(), lik_gaussian.get());
636 }
637 if (sexpat_cov_func &&
638 lengthScaleTiesActive(sexpat_cov_func->getLengthScaleRef().size())) {
639 // Subset selection and identifiability use the same constrained
640 // kernel as the objective, independently of tied members' inputs.
641 Eigen::VectorXd tied = sexpat_cov_func->combineParameters();
643 setParameters(tied);
644 }
645 // The leave-one-out objectives use the pair-distance training geometry
646 // that a composite chart kernel does not have; a charted Sexpat is
647 // fitted on the marginal likelihood, whose gradient the chart kernel
648 // provides in closed form, for the duration of this call.
649 struct ObjectiveOverride {
651 const HyperparameterObjectiveMode saved;
652 ObjectiveOverride(HyperparameterObjectiveMode& s,
653 HyperparameterObjectiveMode mode)
654 : slot(s), saved(s)
655 {
656 slot = mode;
657 }
658 ~ObjectiveOverride()
659 {
660 slot = saved;
661 }
662 };
663 std::optional<ObjectiveOverride> chart_objective;
664 if (sexpat_cov_func && sexpat_cov_func->usesManifoldChart() &&
665 hyperparameter_objective_mode_ != HyperparameterObjectiveMode::NLML) {
666 chart_objective.emplace(hyperparameter_objective_mode_,
668 }
669 has_been_optimized_ = true;
670 last_warm_start_infeasible_ = false;
671 // A length scale held for a pooled subset is held for that fit only.
672 struct ReleaseHeldLengthScales {
673 std::vector<bool>& mask;
674 const bool entry_empty;
675 std::vector<std::size_t> slots;
676 ~ReleaseHeldLengthScales()
677 {
678 if (slots.empty()) return;
679 if (entry_empty) {
680 mask.clear();
681 return;
682 }
683 for (const std::size_t slot: slots)
684 if (slot < mask.size()) mask[slot] = true;
685 }
686 } held_length_scales{scg_opt_settings.active_parameters,
687 scg_opt_settings.active_parameters.empty(),
688 {}};
689
690 if (hyperparameter_optimization_mode_ ==
692 optimizeLaplaceINLA(observation);
693 return;
694 }
695
696 if (use_chem_factorized_hyper_) {
697 optimizeChemistryFactorized(observation);
698 return;
699 }
700
701 const int max_retries = 3; // To prevent potential infinite loops
702 int retry_count = 0;
703 const Eigen::VectorXd fallback_parameters =
704 sexpat_cov_func->combineParameters();
705 bool retry_full_observation = false;
706 bool optimizer_attempted = false;
707
708 while (retry_count <= max_retries) {
709 optimizer_state_->last_input_marginal_likelihood_nonfinite = false;
710 if (wallClockLimitReached()) {
711 failedOptimizer = true;
712 last_fit_stop_reason_ = "wall-clock limit";
713 break;
714 }
715 // 1. Select a subset of data for efficient optimization based on the
716 // current history size.
717 Observation optimization_observation =
718 retry_full_observation ? observation
719 : selectOptimizationSubset(observation);
720 if (!retry_full_observation &&
721 optimization_row_pool_.size() ==
722 static_cast<std::size_t>(observation.R.rows()))
723 for (const std::size_t slot:
724 holdLengthScalesUnresolvedBySubset(optimization_observation))
725 held_length_scales.slots.push_back(slot);
726
727 // The minimizer depends on the selected rows and the start alone: an
728 // append that leaves both as the last converged fit left them has no
729 // objective to minimize, and the new rows are conditioned below at
730 // the fitted theta.
731 if (!retry_full_observation &&
732 subsetFitUnchanged(optimization_observation)) {
733 ++unchanged_subset_fit_skips_;
734 last_fit_evaluations_ = 0;
735 last_fit_budget_evaluations_ = 0;
736 failedOptimizer = false;
737 last_failed_fit_improved_ = false;
738 if (report_level >= 1) {
739 log_man << "The fit subset is unchanged since the last "
740 "converged fit; holding its hyperparameters.\n";
741 }
742 break;
743 }
744 const std::vector<bool> entry_mask = scg_opt_settings.active_parameters;
745 if (optimizer_attempted) PhaseTimers::recordFitRestart();
746 optimizer_attempted = true;
747
748 // 2. Run the numerical optimization on the subset.
749 // Pre-cache inverse distances: positions are fixed during optimization,
750 // only lengthscales change. This avoids redundant coordinate
751 // extractions and norm computations on every iteration.
752 {
753 ScopedPhaseTimer cache_timer(PhaseTimers::cache_seconds);
754 sexpat_cov_func->cacheDistances(optimization_observation.R,
755 optimization_observation.R);
756 }
757 const Eigen::VectorXd fit_start = sexpat_cov_func->combineParameters();
758 const int fit_evaluations_before = PhaseTimers::objective_count;
759 Eigen::VectorXd optimized_parameters =
760 performHyperparameterOptimization(optimization_observation);
761 if (wallClockLimitReached()) {
762 sexpat_cov_func->clearDistanceCache();
763 failedOptimizer = true;
764 last_fit_stop_reason_ = "wall-clock limit";
765 setParameters(fallback_parameters);
766 break;
767 }
768 sexpat_cov_func->clearDistanceCache();
770 std::max(0, PhaseTimers::objective_count - fit_evaluations_before),
771 fit_start.size() > 0 &&
772 optimized_parameters.size() >= fit_start.size() &&
773 (optimized_parameters.head(fit_start.size()) - fit_start)
774 .cwiseAbs()
775 .maxCoeff() <= scg_opt_settings.common.tolerance_sol);
776
777 // A failed stationarity check can still leave a feasible improvement
778 // of the same MAP objective. Preserve it without reporting convergence.
779 if (failedOptimizer) {
780 // A rejected L-BFGS recovery already put the feasible SCG point
781 // in optimized_parameters. Keeping fallback_parameters here would
782 // discard that restore while the stop reason still names it.
783 const bool restored_scg_point =
784 optimizer_state_->last_fallback_rejected;
785 if (report_level >= 1) {
786 log_man << "Hyperparameter optimizer did not converge; "
787 << (restored_scg_point
788 ? "restoring the earlier SCG point.\n"
789 : (last_failed_fit_improved_
790 ? "retaining its feasible MAP "
791 "improvement.\n"
792 : "retaining the input "
793 "hyperparameters.\n"));
794 }
795 setParameters(last_failed_fit_improved_ || restored_scg_point
796 ? optimized_parameters
797 : fallback_parameters);
798 // The estimator is fixed by the configuration, not by the outcome
799 // of the previous attempt: a subset fit that stalls keeps its
800 // objective unless the subset carries no evaluable likelihood.
801 const bool escalate =
802 subset_failure_escalation_ || !last_failed_fit_evaluable_;
803 if (escalate && !retry_full_observation &&
804 optimization_observation.E.size() < observation.E.size()) {
805 retry_full_observation = true;
806 last_warm_start_infeasible_ = false;
807 scg_opt_settings.active_parameters =
808 fullRefitMask(sexpat_cov_func.get(), lik_gaussian.get());
809 mode_refit_policy_.reset();
810 if (report_level >= 1) {
811 log_man << "Retrying the failed subset fit with all "
812 << observation.E.size()
813 << " retained observations and length scales.\n";
814 }
815 continue;
816 }
817 // A non-finite marginal at the input theta is recorded when the
818 // retain above kept that input. A restored SCG point and a
819 // feasible MAP improvement are different points and keep their
820 // own stop reason. An illegal prior does not arrive here as a
821 // NaN: the density throws before it divides by nu or s2.
822 if (!restored_scg_point && !last_failed_fit_improved_ &&
823 optimizer_state_->last_input_marginal_likelihood_nonfinite) {
824 ++optimizer_state_->nonfinite_marginal_likelihood_rejections;
825 last_fit_stop_reason_ = "non-finite marginal likelihood";
826 }
827 break;
828 }
829
830 // 3. Set the new parameters so they can be monitored.
831 setParameters(optimized_parameters);
832 if (retry_full_observation) break;
833 {
834 const double gradient_tolerance =
835 std::min(scg_opt_settings.common.tolerance_func,
836 scg_opt_settings.common.tolerance_sol);
837 if (std::isfinite(last_fit_gradient_norm_) &&
838 last_fit_gradient_norm_ <= gradient_tolerance) {
839 recordConvergedSubsetFit(optimization_observation, entry_mask);
840 } else {
841 converged_subset_fit_.valid = false;
842 }
843 }
844
845 // 4. Monitor for instability. If it returns true, we need to retry.
846 if (use_hod) {
847 bool should_retry =
848 monitorAndAdaptHyperparameters(optimized_parameters);
849
850 if (should_retry) {
851 retry_count++;
852 if (report_level >= 1) {
853 log_man << "Instability detected. Re-running optimization "
854 "with an increased dataset. Attempt "
855 << retry_count << "/" << max_retries << ".\n";
856 }
857 } else {
858 // Stability is acceptable, optimization is complete.
859 if (report_level >= 1) {
860 log_man << "Hyperparameters appear stable. Finalizing "
861 "optimization.\n";
862 }
863 break; // Exit the while loop
864 }
865 } else {
866 // no oscillation check, just exit
867 break; // Exit the while loop
868 }
869 }
870
871 if (retry_count > max_retries) {
872 if (report_level >= 1) {
873 log_man << "Warning: Reached max retries for optimization due to "
874 "persistent instability.\n";
875 }
876 }
877 if (wallClockLimitReached()) return;
878
879 // 5. Update the model's internal state using the full dataset and the last
880 // successful set of hyperparameters.
881 updateModelWithFullData(observation);
882
884 !optimizer_state_->last_fallback_rejected) {
885 if (report_level >= 1) {
886 log_man << "Reverting to the last feasible hyperparameters after "
887 "full-dataset factorization failed.\n";
888 }
889 setParameters(fallback_parameters);
890 updateModelWithFullData(observation);
891 }
892
893 // RFF layered predict: rebuild the random-feature model on the
894 // freshly-fit kernel hyperparameters. Per-fit cost O(N D D_rff +
895 // D_rff^3); per-call mean predict cost then drops from O(N (D+1))
896 // to O(D_rff D), constant in N. Skipped when D_rff <= 0
897 // (default; bit-identical to main). The LaplacePosteriorStamp
898 // policy invalidates the slice/PSIS cache on the same boundary
899 // so RFF stays in sync with the variance arm.
900 // Skip the layered build when updateModelWithFullData already replaced
901 // the exact solve with RFF (rff_replaces_exact_): the model is built
902 // and the eigensolve was skipped, so rebuilding here would be pure
903 // redundant work. The layered path remains for the below-cutoff case
904 // where the exact decompose ran and RFF only accelerates the mean.
905 if (rff_features_requested_ > 0 && is_decomposed_succesfully &&
906 observation.E.size() > 0 && !rff_replaces_exact_) {
907 // Overdetermined-BLR guard: the RFF design matrix has
908 // n_obs * (1 + D) rows and D_rff columns. The Bayesian linear
909 // regression needs the system to be at least 2x overdetermined
910 // for the BLR posterior mean to be well-conditioned (otherwise
911 // the predict mean is dominated by the prior and produces NaN
912 // gradients downstream of the dimer). Skip the build until
913 // the observation count crosses that threshold; the dispatch
914 // then falls back to the cheap-mean MAP predict for the
915 // early outer iters (when N is small enough that MAP is
916 // already cheap anyway).
917 const Eigen::Index n_obs = observation.R.rows();
918 const Eigen::Index D = observation.R.cols();
919 const Eigen::Index n_design = n_obs * (1 + D);
920 if (n_design < 2 * static_cast<Eigen::Index>(rff_features_requested_)) {
921 if (report_level >= 1) {
922 log_man << "RFF layered predict: skipping build (n_design="
923 << n_design
924 << " < 2 * D_rff=" << 2 * rff_features_requested_
925 << "); MAP cross-cov path retained for this iter.\n";
926 }
927 rff_features_ = 0;
928 } else {
929 try {
930 buildRFFModel(observation, rff_features_requested_);
931 if (report_level >= 1) {
932 log_man << "RFF layered predict: built D_rff="
933 << rff_features_requested_ << " features on "
934 << n_obs << " observations (n_design=" << n_design
935 << ", backend="
936 << rff_model_.normalEquationBackendName() << ").\n";
937 }
938 } catch (const std::exception& ex) {
939 // RFF build failure is non-fatal: the dispatch falls
940 // back to MAP cross-cov + matvec. Log and continue.
941 rff_features_ = 0;
942 if (report_level >= 1) {
943 log_man << "RFF build failed: " << ex.what()
944 << "; falling back to exact GP predict.\n";
945 }
946 }
947 }
948 }
949}
void tieLengthScaleParameters(Eigen::VectorXd &theta) const
Sets every tied member to its leader's log length (theta(1 + t)).
Observation selectOptimizationSubset(const Observation &full_observation) const
Select a hyperparameter-optimization subset via FPS-EMD.
void optimizeChemistryFactorized(const Observation &observation)
Chemistry-constrained ARD refit: pairtype lengthscale ratios fixed from descriptor spreads,...
void buildRFFModel(const Observation &training_data, int D_rff)
Definition RFF.cpp:17
bool hasPendingResidualModelRefit() const noexcept
bool hasPendingActivePosteriorRefit() const noexcept
bool monitorAndAdaptHyperparameters(const Eigen::VectorXd &new_parameters)
Monitors hyperparameter history for oscillations and adapts the FPS history size.
void optimizeLaplaceINLA(const Observation &observation)
Definition INLA.cpp:402
void setHyperparameters(const Observation &all_obs, const AtomsConfiguration &conf_info, const bool update_sexpat_cf_param=true, const bool update_const_cf_param=true, const bool update_sqrt_prior_param=true)
Set up hyperparameters for GPR.
std::vector< std::size_t > holdLengthScalesUnresolvedBySubset(const Observation &subset)
Hold, for the next fit, the length scales a pooled subset does not resolve: its inverse-distance feat...
Eigen::VectorXd performHyperparameterOptimization(const Observation &opt_observation)
HyperparameterObjectiveMode
Definition Enums.h:70
static double cache_seconds
Inverse-distance cache built once before the hyperparameter fit.
static void recordFitRestart() noexcept
static double subset_seconds
static double energy_seconds
Objective energy outside factor, solve, eigen, kernel, and curvature.
static double gradient_seconds
static double descriptor_seconds
static void recordFit(long evaluations, bool unmoved) noexcept
static double posterior_seconds

◆ optimizeChemistryFactorized()

void gpr::GaussianProcessRegression::optimizeChemistryFactorized ( const Observation & observation)

Chemistry-constrained ARD refit: pairtype lengthscale ratios fixed from descriptor spreads, global scale on a warm-centered log grid, (prefactor, noise) exact per grid point via the factorized likelihood. A handful of factorizations per refit instead of an SCG trajectory; ratio churn between refits is structurally impossible. Enabled by setChemFactorizedHyperparameters(true); degenerate descriptor scales fall back to the SCG core.

Definition at line 4918 of file Optimize.cpp.

4920{
4921 const Eigen::VectorXd fallback_parameters =
4922 sexpat_cov_func->combineParameters();
4923 const auto stopForWallClock = [&]() {
4924 if (!wallClockLimitReached()) return false;
4925 failedOptimizer = true;
4926 last_fit_stop_reason_ = "wall-clock limit";
4927 setParameters(fallback_parameters);
4928 return true;
4929 };
4930 if (stopForWallClock()) return;
4931 // Chemistry-constrained ARD: per-pairtype lengthscale RATIOS come
4932 // from the descriptor spreads (the same quantity the SCG seed and
4933 // the MAP ls-prior anchor use), leaving a global scale s as the
4934 // only lengthscale degree of freedom. For each s on a warm-centered
4935 // log grid the (prefactor, noise) subproblem is solved exactly by
4936 // the factorized likelihood on one eigendecomposition, so a full
4937 // refit costs a handful of factorizations instead of an SCG
4938 // trajectory's tens of them, and the pairtype ratios cannot churn
4939 // between refits (the sloppy-valley magnitude/lengthscale swings
4940 // die structurally).
4941 // Fallbacks route to the SCG core directly (never back through
4942 // optimize(), which dispatches here when the mode is enabled).
4943 Eigen::VectorXd ratio;
4944 if (!computePairtypeDescriptorScale(observation.R, atoms_config, ratio) ||
4945 ratio.size() == 0 || !(ratio.minCoeff() > 0.0)) {
4947 return;
4948 }
4949 FieldMatrixd& ls = sexpat_cov_func->getLengthScaleRef();
4950 if (ls.size() == 0) {
4952 return;
4953 }
4954 // Normalize ratios to geometric mean 1 so s carries the scale.
4955 const Eigen::VectorXd log_ratio = ratio.array().log();
4956 const double log_gm = log_ratio.mean();
4957 const Eigen::VectorXd unit_ratio = (log_ratio.array() - log_gm).exp();
4958
4959 // Warm start: current fitted geometric-mean lengthscale, or the
4960 // descriptor scale itself on a cold model.
4961 double s_center = std::exp(log_gm);
4962 if (ls.size() > 0 && (ls.array() > 0.0).all()) {
4963 s_center =
4964 std::exp(Eigen::Map<const Eigen::ArrayXd>(ls.data(), ls.size())
4965 .log()
4966 .mean());
4967 }
4968
4969 aux::AuxiliaryFunctionality aux_func;
4970 EigenMatrix opt_R_matrix;
4971 Eigen::VectorXd opt_R_indices;
4972 Eigen::VectorXd opt_energy_and_gradient;
4973 aux_func.assembleMatrixOfRepetitiveCoordinates(observation.R, opt_R_matrix,
4974 opt_R_indices);
4975 aux_func.assembleVectorFromEnergyAndGradient(observation,
4976 opt_energy_and_gradient);
4977 subtractPriorMeanFromTargets(observation.R, observation.E.size(),
4978 opt_energy_and_gradient);
4979 standardizeTargets(opt_energy_and_gradient, observation.E.size());
4980
4981 const auto fillLengthscales = [&](double s) {
4982 Eigen::Index k = 0;
4983 for (Eigen::Index r = 0; r < ls.rows(); ++r) {
4984 for (Eigen::Index c = 0; c < ls.cols(); ++c) {
4985 const Eigen::Index pt = ls.cols() > 1 ? c : r;
4986 const double ratio_pt =
4987 pt < unit_ratio.size() ? unit_ratio(pt) : 1.0;
4988 ls(r, c) = s * ratio_pt;
4989 ++k;
4990 }
4991 }
4992 (void)k;
4993 };
4994
4995 // 7-point log grid, half-decade span around the warm center: the
4996 // NLML in s is unimodal over far wider ranges in practice, and the
4997 // cadence keeps consecutive optima close.
4998 constexpr int kGridPoints = 7;
4999 constexpr double kLogSpan = 0.5 * 2.302585092994046; // half a decade
5000 struct GridCandidate {
5001 double s = 0.0;
5002 double prefactor = 0.0;
5003 double noise = 0.0;
5004 double nlml = std::numeric_limits<double>::infinity();
5005 };
5006 std::vector<GridCandidate> candidates;
5007 candidates.reserve(kGridPoints);
5008 for (int g = 0; g < kGridPoints; ++g) {
5009 if (stopForWallClock()) return;
5010 const double t = kGridPoints > 1
5011 ? -1.0 + 2.0 * static_cast<double>(g) /
5012 static_cast<double>(kGridPoints - 1)
5013 : 0.0;
5014 const double s = s_center * std::exp(t * kLogSpan);
5015 fillLengthscales(s);
5016 const ProfiledKernelScale scale = profileUnitKernelScale(
5017 *this, opt_R_matrix, opt_R_indices, opt_energy_and_gradient);
5018 if (!scale.ok) continue;
5019 // noise is the observation variance sf2 * rho, not the ratio rho.
5020 candidates.push_back({s, scale.signal, scale.noise, scale.nlml});
5021 }
5022 if (candidates.empty()) {
5024 return;
5025 }
5026 std::sort(candidates.begin(), candidates.end(),
5027 [](const GridCandidate& a, const GridCandidate& b) {
5028 return a.nlml < b.nlml;
5029 });
5030
5031 // Physics-informed selection (constrained empirical Bayes): among
5032 // the top NLML candidates, reject those whose posterior energy
5033 // profile along the collocation path (the live band, the discrete
5034 // IRC) oscillates. A single-barrier valley profile has total
5035 // variation ~ 2x its range; a churned-lengthscale posterior
5036 // wiggles and its TV blows past that. The bound is scale-free, so
5037 // there is no penalty weight to tune; if every candidate fails the
5038 // filter, pure NLML decides (the filter constrains, never
5039 // invents).
5040 // Derived filter (scripts/derive_chem_factorized_hyper.py): a
5041 // piecewise-monotone profile with at most B barriers satisfies
5042 // TV <= 2 B range exactly, and predictive noise sigma_i moves the
5043 // measured TV by at most sigma_TV = sum_i (sigma_i + sigma_{i-1}).
5044 // Reject a candidate only when its profile exceeds the B-barrier
5045 // bound SIGNIFICANTLY: TV - 2 B range > sigma_TV. At low data the
5046 // predictive sigmas are large, sigma_TV dominates, and the filter
5047 // self-disables; no separate low-data guard exists.
5048 // kMaxBarriers = 2 is a chemistry assumption (one intermediate
5049 // along the band), not a tuning constant.
5050 auto bandProfileAccepted = [&](const GridCandidate& c) {
5051 if (wallClockLimitReached()) return false;
5052 if (physics_collocation_path_.rows() < 4) return true;
5053 fillLengthscales(c.s);
5054 sexpat_cov_func->setMagnSigma2(c.prefactor);
5055 lik_gaussian->setSigma2(c.noise);
5056 sigma2 = trainingToPhysicalNoiseVariance(c.noise);
5057 updateModelWithFullData(observation);
5058 const Eigen::Index m = physics_collocation_path_.rows();
5059 Eigen::VectorXd profile(m);
5060 Eigen::VectorXd sigma(m);
5061 for (Eigen::Index i = 0; i < m; ++i) {
5062 if (wallClockLimitReached()) return false;
5063 gpr::Observation probe;
5064 probe.R.resize(1, physics_collocation_path_.cols());
5065 probe.R.row(0) = physics_collocation_path_.row(i);
5067 if (probe.E.size() == 0 || !std::isfinite(probe.E(0, 0)))
5068 return true; // no usable profile: do not filter
5069 profile(i) = probe.E(0, 0);
5070 gpr::Observation variance_probe;
5071 variance_probe.R.resize(1, physics_collocation_path_.cols());
5072 variance_probe.R.row(0) = physics_collocation_path_.row(i);
5073 calculateVarianceDispatched(variance_probe);
5074 const double energy_variance =
5075 variance_probe.E.size() > 0 ? variance_probe.E(0, 0) : 0.0;
5076 sigma(i) = std::isfinite(energy_variance) && energy_variance > 0.0
5077 ? std::sqrt(energy_variance)
5078 : 0.0;
5079 }
5080 const double range = profile.maxCoeff() - profile.minCoeff();
5081 if (!(range > 0.0)) return true;
5082 double total_variation = 0.0;
5083 double sigma_tv = 0.0;
5084 for (Eigen::Index i = 1; i < m; ++i) {
5085 total_variation += std::abs(profile(i) - profile(i - 1));
5086 sigma_tv += sigma(i) + sigma(i - 1);
5087 }
5088 constexpr int kMaxBarriers = 2;
5089 const double bound = 2.0 * kMaxBarriers * range;
5090 return total_variation - bound <= sigma_tv;
5091 };
5092
5093 constexpr int kPhysicsCheckedCandidates = 3;
5094 const GridCandidate* selected = nullptr;
5095 const int check_count = std::min<int>(kPhysicsCheckedCandidates,
5096 static_cast<int>(candidates.size()));
5097 for (int c = 0; c < check_count; ++c) {
5098 if (bandProfileAccepted(candidates[static_cast<std::size_t>(c)])) {
5099 selected = &candidates[static_cast<std::size_t>(c)];
5100 break;
5101 }
5102 if (stopForWallClock()) return;
5103 }
5104 if (selected == nullptr) selected = &candidates.front();
5105
5106 fillLengthscales(selected->s);
5107 sexpat_cov_func->setMagnSigma2(selected->prefactor);
5108 lik_gaussian->setSigma2(selected->noise);
5109 sigma2 = trainingToPhysicalNoiseVariance(selected->noise);
5110 if (this->report_level >= 2) {
5111 log_man << "Chem-factorized optimization: s=" << selected->s
5112 << " noise=" << selected->noise
5113 << " prefactor=" << selected->prefactor
5114 << " NLML=" << selected->nlml << " (rank "
5115 << (selected - candidates.data()) << " after physics filter)"
5116 << "\n";
5117 }
5118 if (stopForWallClock()) return;
5119 updateModelWithFullData(observation);
5120}
static bool computePairtypeDescriptorScale(const Coord &R, const AtomsConfiguration &conf_info, Eigen::VectorXd &ls_k)
Per-pairtype motion scale rho0_k = sqrt(sum_f var(1/r_f)). Each pair feature is centered across confi...
FieldMatrixd E

◆ optimizeFactorized()

void gpr::GaussianProcessRegression::optimizeFactorized ( const Observation & observation)

Alternative optimization via eigendecomposition + noise grid search.

Assembles the unit signal sexpat kernel without observation noise, eigendecomposes it, then uses FactorizedLikelihood and NoiseGridSearch. The analytical prefactor is the signal variance. The installed observation noise is that prefactor times the profiled noise to signal ratio.

Only works for isotropic lengthscale (single lengthscale for all pairtypes). For ARD, falls back to optimize().

Parameters
observationThe full set of observed data.

Definition at line 4491 of file Optimize.cpp.

4493{
4494 // For ARD (multiple lengthscales per pairtype), the factorized path
4495 // does not apply. Fall back to the SCG-based optimizer.
4496 if (sexpat_cov_func->getLengthScaleRef().cols() > 1) {
4497 optimize(observation);
4498 return;
4499 }
4500
4501 aux::AuxiliaryFunctionality aux_func;
4502 EigenMatrix opt_R_matrix;
4503 Eigen::VectorXd opt_R_indices;
4504 Eigen::VectorXd opt_energy_and_gradient;
4505
4506 // Assemble training coordinates and targets
4507 aux_func.assembleMatrixOfRepetitiveCoordinates(observation.R, opt_R_matrix,
4508 opt_R_indices);
4509 aux_func.assembleVectorFromEnergyAndGradient(observation,
4510 opt_energy_and_gradient);
4511 subtractPriorMeanFromTargets(observation.R, observation.E.size(),
4512 opt_energy_and_gradient);
4513 standardizeTargets(opt_energy_and_gradient, observation.E.size());
4514
4515 // Kt is the unit signal kernel. The grid variable is rho, and the
4516 // observation noise installed below is sf2 * rho.
4517 const ProfiledKernelScale scale = profileUnitKernelScale(
4518 *this, opt_R_matrix, opt_R_indices, opt_energy_and_gradient);
4519 if (!scale.ok) {
4520 failedOptimizer = true;
4521 return;
4522 }
4523 failedOptimizer = false;
4524
4525 sexpat_cov_func->setMagnSigma2(scale.signal);
4526 lik_gaussian->setSigma2(scale.noise);
4527 sigma2 = trainingToPhysicalNoiseVariance(scale.noise);
4528
4529 if (this->report_level >= 2) {
4530 log_man << "Factorized optimization: noise=" << scale.noise
4531 << " prefactor=" << scale.signal << " NLML=" << scale.nlml
4532 << "\n";
4533 }
4534
4535 // Rebuild the model with optimal parameters using the full dataset
4536 updateModelWithFullData(observation);
4537}
void optimize(const Observation &observation)
Optimize paramaters of a Gaussian process.
Definition Optimize.cpp:550

◆ optimizeLaplaceINLA()

void gpr::GaussianProcessRegression::optimizeLaplaceINLA ( const Observation & observation)
protected

Definition at line 402 of file INLA.cpp.

404{
405 failedOptimizer = false;
406 const Eigen::VectorXd fallback_parameters = packInlaHyperparameters();
407 if (wallClockLimitReached()) {
408 failedOptimizer = true;
409 last_fit_stop_reason_ = "wall-clock limit";
410 return;
411 }
412
413 Observation optimization_observation =
414 selectOptimizationSubset(observation);
415
416 aux::AuxiliaryFunctionality aux_func;
417 EigenMatrix opt_R_matrix;
418 Eigen::VectorXd opt_R_indices;
419 Eigen::VectorXd opt_energy_and_gradient;
420 aux_func.assembleMatrixOfRepetitiveCoordinates(optimization_observation.R,
421 opt_R_matrix, opt_R_indices);
422 aux_func.assembleVectorFromEnergyAndGradient(optimization_observation,
423 opt_energy_and_gradient);
424 subtractPriorMeanFromTargets(optimization_observation.R,
425 optimization_observation.E.size(),
426 opt_energy_and_gradient);
427 standardizeTargets(opt_energy_and_gradient,
428 optimization_observation.E.size());
429
430 // The dest Newton/RFO mode-finder (computeInlaPosteriorMode) walks
431 // through NLML + Hessian evaluations per outer dimer iter on the
432 // optimisation subset. Each evaluateEnergy rebuilds the training
433 // covariance matrix; without a distance cache, every rebuild
434 // recomputes the per-pair inverse distances even though the subset
435 // coordinates are fixed across the inner loop. Mirror the SCG
436 // path's cacheDistances / clearDistanceCache discipline (see
437 // performHyperparameterOptimization in Optimize.cpp) so the inner
438 // NLML evals hit the dist_calculator_ cache. Only the
439 // hyperparameters change between inner iters; positions are
440 // constant. RgminScg is the SCG waist.
441 if (sexpat_cov_func != nullptr) {
442 sexpat_cov_func->cacheDistances(optimization_observation.R,
443 optimization_observation.R);
444 }
445
446 // Build the same per-outer-iter geometry handle the SCG driver uses
447 // (Optimize.cpp). The INLA dest Newton/RFO mode finder also evaluates
448 // the marginal log likelihood + gradient + Hessian at fixed training
449 // inputs, so the K-assembly and dK/dtheta geometry path applies.
450 TrainingKernelGeometry inla_geom;
451 const bool inla_geom_ready =
453 prepareTrainingKernelGeometry(opt_R_matrix, opt_R_indices, inla_geom);
454 const TrainingKernelGeometry* inla_geom_ptr =
455 inla_geom_ready ? &inla_geom : nullptr;
456
457 Eigen::VectorXd theta_mode;
458 const bool mode_ok = computeInlaPosteriorMode(opt_R_matrix, opt_R_indices,
459 opt_energy_and_gradient,
460 theta_mode, inla_geom_ptr);
461
462 if (sexpat_cov_func != nullptr) {
463 sexpat_cov_func->clearDistanceCache();
464 }
465
466 if (!mode_ok) {
467 failedOptimizer = true;
468 setParameters(fallback_parameters);
469 if (wallClockLimitReached()) {
470 last_fit_stop_reason_ = "wall-clock limit";
471 return;
472 }
473 updateModelWithFullData(observation);
474 return;
475 }
476
477 setParameters(theta_mode);
478 if (wallClockLimitReached()) {
479 failedOptimizer = true;
480 last_fit_stop_reason_ = "wall-clock limit";
481 setParameters(fallback_parameters);
482 return;
483 }
484 updateModelWithFullData(observation);
486 failedOptimizer = true;
487 setParameters(fallback_parameters);
488 updateModelWithFullData(observation);
489 }
490}

◆ optimizeMarginalLikelihood()

GaussianProcessRegression::MarginalLikelihoodReport gpr::GaussianProcessRegression::optimizeMarginalLikelihood ( const Observation & observation)
nodiscard

Fit by the Gaussian negative log marginal likelihood alone. The optimizer's MAP prior and barrier penalties are disabled; the positive parameter domain remains part of the covariance definition.

Definition at line 952 of file Optimize.cpp.

954{
955 detail::requireJointTrainingObservation(
956 observation, "GaussianProcessRegression::optimizeMarginalLikelihood");
957 if (model_profile_ != GPModelProfile::EXTENDED)
958 throw std::logic_error(
959 "prior-free marginal likelihood requires the EXTENDED model "
960 "profile");
961 if (atomic_environment_model_)
962 throw std::logic_error(
963 "prior-free marginal likelihood is unavailable for the atomic "
964 "environment model");
965
966 sexpat_cov_func->clearHierarchicalPrior();
967 sexpat_cov_func->clearPcLengthScalePrior();
968 sexpat_cov_func->setUseLogNormalMagnPrior(false);
969 lik_gaussian->setOptimizeSigma2(true);
970 // The companion fixed-parameter update is a Cholesky bordering
971 // operation, so retain that exact factor as the fitted posterior.
972 setHssvdBackend(false);
974
975 struct Restore {
976 bool& flag;
977 bool saved;
978 int& history;
979 int saved_history;
980 int& latest;
981 int saved_latest;
982 bool& scg_stalled;
983 bool saved_scg_stalled;
984 ScgStallScope& scg_stall_scope;
985 ScgStallScope saved_scg_stall_scope;
986 ~Restore()
987 {
988 flag = saved;
989 history = saved_history;
990 latest = saved_latest;
991 scg_stalled = saved_scg_stalled;
992 scg_stall_scope = std::move(saved_scg_stall_scope);
993 }
994 } restore{unregularized_marginal_likelihood_,
995 unregularized_marginal_likelihood_,
996 fps_options.history,
997 fps_options.history,
998 fps_options.latest_points,
999 fps_options.latest_points,
1000 scg_stalled_,
1001 scg_stalled_,
1002 scg_stall_scope_,
1003 scg_stall_scope_};
1004 // Switching to the prior-free marginal-likelihood objective or enabling
1005 // the trailing noise parameter changes the objective landscape and
1006 // parameter dimension: any warm quasi-Newton session or SCG-stall state
1007 // from an earlier MAP fit no longer describes this problem. The latch
1008 // is cleared only after Restore has saved the caller's copy.
1010 unregularized_marginal_likelihood_ = true;
1011 scg_stalled_ = false;
1012 scg_stall_scope_ = {};
1013 // This API fits the likelihood of exactly the supplied data, not the
1014 // adaptive optimization subset used by long-running searches.
1015 fps_options.history = static_cast<int>(observation.R.rows());
1016 fps_options.latest_points = 0;
1017 optimize(observation);
1018 int optimizer_restarts = 0;
1019 if (failedOptimizer) {
1020 // Safety net when the first start fails: if it did not reach a
1021 // decomposed signal-dominated iterate, reseed covariance and noise
1022 // scales from the observation's energy variance and descriptor
1023 // spread; otherwise continue from the retained feasible iterate
1024 // keeping its 3D quasi-Newton curvature memory.
1025 const int first_pass_iterations = last_fit_iterations_;
1026 if (!last_failed_fit_improved_ || !is_decomposed_succesfully ||
1027 !(lik_gaussian->getSigma2() > 0.0 &&
1028 lik_gaussian->getSigma2() < 1.0 &&
1029 std::isfinite(lik_gaussian->getSigma2()))) {
1030 const double noise_seed =
1031 (jitter_sigma2 > 0.0 && std::isfinite(jitter_sigma2))
1032 ? std::max(1.0e-4, jitter_sigma2)
1033 : 1.0e-4;
1034 // Reseeding installs the configured length-scale priors again.
1035 auto prior_state = sexpat_cov_func->priorState();
1036 setHyperparameters(observation, atoms_config, true, true, true);
1037 sexpat_cov_func->restorePriorState(std::move(prior_state));
1038 lik_gaussian->setSigma2(noise_seed);
1039 sigma2 = trainingToPhysicalNoiseVariance(noise_seed);
1040 invalidateLikelihoodNoiseDependentState();
1041 scg_stalled_ = false;
1042 scg_stall_scope_ = {};
1044 }
1045 failedOptimizer = false;
1046 ++optimizer_restarts;
1047 optimize(observation);
1048 last_fit_iterations_ += first_pass_iterations;
1049 }
1050 last_fit_restarts_ = optimizer_restarts;
1051 if (failedOptimizer)
1052 throw std::runtime_error(
1053 "prior-free marginal-likelihood optimizer did not converge");
1056 throw std::runtime_error(
1057 "prior-free marginal-likelihood fit did not produce a posterior");
1058
1060 const double output_scale = outputScale();
1061 if (!(output_scale > 0.0) || !std::isfinite(output_scale))
1062 throw std::runtime_error(
1063 "prior-free marginal-likelihood output scale is invalid");
1064 Eigen::Index report_rows = b.size();
1065 double log_determinant = 2.0 * trainingSolver().halfLogDeterminant();
1066 double quadratic = b.squaredNorm();
1067 if (rigid_deflation_.isActiveForFullOrder(R_matrix.rows())) {
1068 report_rows = R_matrix.rows();
1069 log_determinant += rigid_deflation_.rigid_logdet_only;
1070 quadratic += rigid_deflation_.rigid_quad_term;
1071 }
1072#ifdef GPR_LINALG_KOKKOS
1073 if (hasDevicePosterior()) {
1074 const auto parts = device_posterior_->objectiveParts();
1075 report_rows = device_posterior_->order();
1076 log_determinant = 2.0 * parts[0];
1077 quadratic = parts[1];
1078 }
1079#endif
1080 const double physical_log_scale =
1081 static_cast<double>(report_rows) * 2.0 * numerics::log(output_scale);
1082 report.log_determinant = log_determinant + physical_log_scale;
1083 report.quadratic = quadratic;
1084 report.objective =
1085 0.5 * static_cast<double>(report_rows) * numerics::log(2.0 * M_PI) +
1086 0.5 * report.log_determinant + 0.5 * report.quadratic;
1087 if (!std::isfinite(report.objective))
1088 throw std::runtime_error(
1089 "prior-free marginal-likelihood objective is not finite");
1090 report.signal_variance =
1091 trainingToPhysicalNoiseVariance(sexpat_cov_func->getMagnSigma2());
1092 report.noise_variance = sigma2;
1093 report.length_scales = Eigen::Map<const Eigen::VectorXd>(
1094 sexpat_cov_func->getLengthScaleRef().data(),
1095 sexpat_cov_func->getLengthScaleRef().size());
1096 report.iterations = last_fit_iterations_;
1097 report.optimizer_restarts = optimizer_restarts;
1098 return report;
1099}
void setHyperparameterObjectiveMode(HyperparameterObjectiveMode mode) noexcept
void setHssvdBackend(bool enabled) noexcept
Result of a prior-free negative log marginal-likelihood fit.

◆ outputMean()

double gpr::GaussianProcessRegression::outputMean ( ) const
inlinenodiscardnoexcept

Definition at line 1741 of file GaussianProcessRegression.h.

1742 {
1743 return y_mean_;
1744 }

◆ outputMeanFrozen()

bool gpr::GaussianProcessRegression::outputMeanFrozen ( ) const
inlinenodiscardnoexcept

Definition at line 1749 of file GaussianProcessRegression.h.

1750 {
1751 return y_mean_frozen_;
1752 }

◆ outputScale()

double gpr::GaussianProcessRegression::outputScale ( ) const
inlinenodiscardnoexcept

Definition at line 1745 of file GaussianProcessRegression.h.

1746 {
1747 return y_scale_;
1748 }

◆ outputScaleFloor()

bool gpr::GaussianProcessRegression::outputScaleFloor ( ) const
inlinenodiscardnoexcept

Definition at line 1727 of file GaussianProcessRegression.h.

1728 {
1729 return output_scale_floor_;
1730 }

◆ packInlaHyperparameters()

Eigen::VectorXd gpr::GaussianProcessRegression::packInlaHyperparameters ( ) const
nodiscard

Pack the current hyperparameters into the same flat vector layout consumed by ~setParameters~. The trailing log(sigma_n^2) likelihood-noise coordinate is included only when the active theta owns that coordinate. Inverse of ~setParameters~; suitable for snapshot / restore.

Definition at line 494 of file GaussianProcessRegression.cpp.

495{
496 if (sexpat_cov_func == nullptr) return {};
497 Eigen::VectorXd theta = sexpat_cov_func->combineParameters();
498 if (!theta_includes_likelihood_noise_) return theta;
499
500 const double noise = likelihoodNoiseVariance();
501 if (!(noise > 0.0)) return {};
502
503 Eigen::VectorXd packed(theta.size() + 1);
504 packed.head(theta.size()) = theta;
505 packed(packed.size() - 1) = numerics::log(noise);
506 return packed;
507}

◆ pairLocalTilesEnabled()

bool gpr::GaussianProcessRegression::pairLocalTilesEnabled ( ) const
inlinenodiscardnoexcept

Definition at line 1935 of file GaussianProcessRegression.h.

1936 {
1937 return use_pair_local_tiles_;
1938 }

◆ parkTrainingCholeskyFactor()

bool gpr::GaussianProcessRegression::parkTrainingCholeskyFactor ( )

Move this model's distributed training factor out of the process-wide ScaLAPACK solve slot while another GP owns it.

Definition at line 289 of file Decompose.cpp.

290{
291#ifdef GPR_LINALG_SCALAPACK
292 if (!training_cholesky_is_distributed_) return false;
293 auto& state = backend().distributed();
294 auto snapshot = state.take_cached_L(this);
295 if (!snapshot.valid()) return false;
296 parked_training_cholesky_ = std::move(snapshot);
297 return true;
298#else
299 return false;
300#endif
301}

◆ performHyperparameterOptimization()

Eigen::VectorXd gpr::GaussianProcessRegression::performHyperparameterOptimization ( const Observation & opt_observation)
protected

Definition at line 2076 of file Optimize.cpp.

2078{
2082 "this fit",
2083 "the objective has no exact NLML Hessian-vector product");
2084 }
2085 if (const char* path = std::getenv("GPR_TRAINING_AUDIT")) {
2086 // Audit ownership follows the model's communicator, including
2087 // fits that have not configured a distributed factorization grid.
2088 if (backend().mpi().rank == 0) {
2089 std::ofstream audit(path, std::ios::app);
2090 if (!audit)
2091 throw std::runtime_error("cannot open GP training audit");
2092 audit << std::setprecision(17) << "fit " << opt_observation.R.rows()
2093 << ' ' << outputMean() << ' ' << outputScale() << '\n';
2094 for (Eigen::Index row = 0; row < opt_observation.R.rows(); ++row)
2095 audit << "row " << row << ' ' << opt_observation.R.row(row)
2096 << ' ' << opt_observation.E.data()[row] << ' '
2097 << opt_observation.G.row(row) << '\n';
2098 }
2099 }
2100 last_scg_fallback_used_ = false;
2101 optimizer_state_->last_fallback_rejected = false;
2102 // Steps the SCG attempt finished before the L-BFGS fallback of the
2103 // same call. A stall skip does not run SCG, so this stays zero and
2104 // the reported count is the fallback alone. A later tie-release
2105 // refit replaces both, because that refit owns the accepted point.
2106 int scg_steps_before_fallback = 0;
2107 last_failed_fit_improved_ = false;
2108 last_failed_fit_evaluable_ = true;
2109 last_fit_gradient_norm_ = std::numeric_limits<double>::quiet_NaN();
2110 last_fit_configurations_ = static_cast<std::size_t>(
2111 std::max<Eigen::Index>(0, opt_observation.R.rows()));
2112 struct OneRefitMask {
2113 std::vector<bool>& mask;
2114 ~OneRefitMask()
2115 {
2116 mask.clear();
2117 }
2118 } one_refit_mask{scg_opt_settings.active_parameters};
2119 // Rows that all lie within one length scale of each other identify only
2120 // the ratio of amplitude to length scale: the likelihood is flat along
2121 // m / l^2 = F^2 and the optimizer runs to the length-scale floor with a
2122 // vanishing amplitude (14_hydro's supplied-seed dimer: two rows 0.01 A
2123 // apart, mag2 7e-7 and every length at the 0.02 floor, kept through 39
2124 // rows by warm starts). Such rows hold the length scales where they are
2125 // and fit the amplitude and noise; the lengths move once the rows spread
2126 // past one length scale, the kernel's own support scale.
2127 if (scg_opt_settings.active_parameters.empty() && sexpat_cov_func &&
2128 opt_observation.R.rows() > 1 && !sexpat_cov_func->usesManifoldChart() &&
2129 sexpat_cov_func->getLengthScaleRef().size() > 0) {
2130 FieldMatrixd scores;
2131 sexpat_cov_func->correlationDistances(
2132 opt_observation.R, opt_observation.R, atoms_config, scores);
2133 double farthest = 0.0;
2134 bool finite = scores.rows() == opt_observation.R.rows();
2135 for (Eigen::Index i = 0; finite && i < scores.rows(); ++i)
2136 for (Eigen::Index j = i + 1; j < scores.cols(); ++j) {
2137 if (!std::isfinite(scores(i, j))) {
2138 finite = false;
2139 break;
2140 }
2141 farthest = std::max(farthest, scores(i, j));
2142 }
2143 if (finite && farthest < 1.0) {
2144 const Eigen::Index lengths =
2145 sexpat_cov_func->getLengthScaleRef().size();
2146 auto& mask = scg_opt_settings.active_parameters;
2147 mask.assign(
2148 static_cast<std::size_t>(1 + lengths) +
2149 (lik_gaussian && lik_gaussian->getOptimizeSigma2() ? 1 : 0),
2150 true);
2151 std::fill(mask.begin() + 1, mask.begin() + 1 + lengths, false);
2152 if (report_level >= 1)
2153 log_man << "Hyperparameter identifiability: the training rows "
2154 "lie within "
2155 << farthest
2156 << " length scales of each other; holding the length "
2157 "scales and fitting the amplitude.\n";
2158 }
2159 }
2160 aux::AuxiliaryFunctionality aux_func;
2161 Eigen::MatrixXd opt_R_matrix;
2162 Eigen::VectorXd opt_R_indices;
2163 Eigen::VectorXd opt_energy_and_gradient;
2164 // The fit's block geometry lives for the fit.
2165 struct FitGeometryLease {
2166 const GaussianProcessRegression& model;
2167 ~FitGeometryLease()
2168 {
2169 model.releaseFitGeometry();
2170 }
2171 } fit_geometry_lease{*this};
2172
2173 aux_func.assembleMatrixOfRepetitiveCoordinates(opt_observation.R,
2174 opt_R_matrix, opt_R_indices);
2175 aux_func.assembleVectorFromEnergyAndGradient(opt_observation,
2176 opt_energy_and_gradient);
2177 subtractPriorMeanFromTargets(opt_observation.R, opt_observation.E.size(),
2178 opt_energy_and_gradient);
2179 Eigen::VectorXd parameters_cf = sexpat_cov_func->combineParameters();
2180 const OptimizationObjectiveFrame objective_frame =
2182 opt_energy_and_gradient, opt_observation.E.size(), &parameters_cf);
2183 const Eigen::Index covariance_parameter_count = parameters_cf.size();
2184 // Learned likelihood noise: append log(sigma2) AFTER the frame entry
2185 // so the entry carries frame units (the frame already rescaled the
2186 // lik sigma2 by 1/target_scale^2, exactly the transform the
2187 // log-magnitude entry received); leaveOptimizationObjectiveFrame
2188 // un-shifts it symmetrically and the caller's setParameters applies
2189 // the physical value.
2190 if (lik_gaussian && lik_gaussian->getOptimizeSigma2()) {
2191 const double frame_sigma2 = lik_gaussian->getSigma2();
2192 if (std::isfinite(frame_sigma2) && frame_sigma2 > 0.0) {
2193 const Eigen::Index n0 = parameters_cf.size();
2194 parameters_cf.conservativeResize(n0 + 1);
2195 parameters_cf(n0) = std::log(frame_sigma2);
2196 }
2197 }
2198 double log_lengthscale_lower = -std::numeric_limits<double>::infinity();
2199 if (opt_observation.R.rows() > 0 && opt_observation.R.cols() > 0) {
2200 aux::Distance distance;
2201 FieldMatrixd dist;
2202 FieldMatrixd unit_lengthscale(1, 1);
2203 unit_lengthscale.setConstant(1.0);
2204 distance.dist_at(opt_observation.R, opt_observation.R, atoms_config,
2205 unit_lengthscale, dist);
2206 if (dist.size() > 0 && dist.allFinite()) {
2207 const double min_lengthscale =
2208 lengthscaleProjectionFloor(dist.maxCoeff(), lengthscale_floor_);
2209 if (std::isfinite(min_lengthscale) && min_lengthscale > 0.0) {
2210 log_lengthscale_lower = std::log(min_lengthscale);
2211 }
2212 }
2213 }
2214 const auto project_lengthscales_to_domain = [&](Eigen::VectorXd& theta) {
2215 if (!std::isfinite(log_lengthscale_lower) || theta.size() <= 1) return;
2216 const double interior_lower = std::nextafter(
2217 log_lengthscale_lower, std::numeric_limits<double>::infinity());
2218 for (Eigen::Index i = 1; i < covariance_parameter_count; ++i) {
2219 if (!(theta(i) > log_lengthscale_lower)) theta(i) = interior_lower;
2220 }
2221 };
2222 if (std::isfinite(log_lengthscale_lower) &&
2223 scg_opt_settings.active_parameters.size() ==
2224 static_cast<std::size_t>(parameters_cf.size())) {
2225 for (Eigen::Index i = 1; i < covariance_parameter_count; ++i) {
2226 if (!scg_opt_settings
2227 .active_parameters[static_cast<std::size_t>(i)] &&
2228 !(parameters_cf(i) > log_lengthscale_lower)) {
2229 scg_opt_settings.active_parameters.clear();
2230 mode_refit_policy_.reset();
2231 if (report_level >= 1) {
2232 log_man << "A fixed length scale is outside the fitted "
2233 "domain; refitting all length scales.\n";
2234 }
2235 break;
2236 }
2237 }
2238 }
2239 const bool ties_active =
2240 lengthScaleTiesActive(covariance_parameter_count - 1);
2241 // The mask before the ties: which length scales the data identify.
2242 // An empty mask means every parameter is fitted; the mask is left as
2243 // it is, since a non-empty mask also marks the active-subspace refit
2244 // regime for the code after the fit.
2245 const std::vector<bool> identifiable_mask =
2246 scg_opt_settings.active_parameters;
2247 // Tied members start at their leader's scale; the structure (mask,
2248 // bounds, priors) is applied once the MAP configuration exists.
2249 if (ties_active) tieLengthScaleParameters(parameters_cf);
2250 project_lengthscales_to_domain(parameters_cf);
2251 Eigen::VectorXd old_parameters_cf = parameters_cf;
2252 Eigen::VectorXd parameter_lower = Eigen::VectorXd::Constant(
2253 parameters_cf.size(), -std::numeric_limits<double>::infinity());
2254 Eigen::VectorXd parameter_upper = -parameter_lower;
2255 if (std::isfinite(log_lengthscale_lower) &&
2256 covariance_parameter_count > 1) {
2257 parameter_lower.segment(1, covariance_parameter_count - 1)
2258 .setConstant(
2259 std::nextafter(log_lengthscale_lower,
2260 std::numeric_limits<double>::infinity()));
2261 }
2262 // The bounds before any parameter is pinned: a released tie member
2263 // returns to these.
2264 const Eigen::VectorXd general_lower = parameter_lower;
2265 const Eigen::VectorXd general_upper = parameter_upper;
2266 if (scg_opt_settings.active_parameters.size() ==
2267 static_cast<std::size_t>(parameters_cf.size())) {
2268 for (Eigen::Index i = 0; i < parameters_cf.size(); ++i) {
2269 if (!scg_opt_settings
2270 .active_parameters[static_cast<std::size_t>(i)]) {
2271 parameter_lower(i) = parameters_cf(i);
2272 parameter_upper(i) = parameters_cf(i);
2273 }
2274 }
2275 }
2276
2277 // Scale-free MAP lengthscale-prior anchor: rho0_k = per-pairtype
2278 // descriptor std, the same data-derived scale setHyperparameters uses to
2279 // seed the length scales (see computePairtypeDescriptorScale). Computed
2280 // once per hyperparameter-optimization call (not per rgmin SCG or L-BFGS
2281 // probe). Left empty when the descriptor spread is degenerate (no
2282 // positions, or a pairtype has fewer than two observations); the shared
2283 // MAP objective then falls back to its raw-unit Student-t prior
2284 // (MapObjective.h), matching the pre-fix behaviour exactly.
2285 Eigen::VectorXd lengthscale_rho0;
2286 computePairtypeDescriptorScale(opt_observation.R, atoms_config,
2287 lengthscale_rho0);
2288 poolDescriptorScaleByTies(lengthscale_rho0);
2289 if (ls_seed_chemical_floor_ && lengthscale_rho0.size() > 0 &&
2290 lengthscale_rho0.size() == atoms_config.n_pt) {
2291 // The MAP prior anchors each length scale at rho0_k; floor it the
2292 // way the seed is floored so the prior does not pull a barely
2293 // moving pair back to its collapsed spread.
2294 const priors::CovalentBondPrior bond_prior(atoms_config);
2295 const Eigen::VectorXd chemical =
2296 bond_prior.lengthScalePerPairtype().cwiseInverse();
2297 for (Eigen::Index k = 0; k < lengthscale_rho0.size(); ++k) {
2298 if (std::isfinite(chemical(k)) && chemical(k) > 0.0)
2299 lengthscale_rho0(k) =
2300 std::max(lengthscale_rho0(k), chemical(k));
2301 }
2302 }
2303
2304 // A pair type the population prior has seen is anchored at the
2305 // campaign's location for its element pair (after the tie pooling: the
2306 // members of a group share the element pair and so the anchor).
2307 if (!population_prior_.empty() && atoms_config.n_pt > 0) {
2308 const auto entries = population_prior_.perPairtype(atoms_config);
2309 // Without a descriptor scale (too few rows per pair type) the
2310 // population still anchors the types it has seen; the others fall
2311 // back per index as before.
2312 if (lengthscale_rho0.size() != atoms_config.n_pt)
2313 lengthscale_rho0 = Eigen::VectorXd::Constant(
2314 atoms_config.n_pt, std::numeric_limits<double>::quiet_NaN());
2315 for (Eigen::Index k = 0; k < lengthscale_rho0.size(); ++k) {
2316 const auto* entry = entries[static_cast<std::size_t>(k)];
2317 if (entry != nullptr)
2318 lengthscale_rho0(k) = std::exp(entry->log_length_mu);
2319 }
2320 }
2321
2322 // The coordinate box excludes collapsed length scales without adding a
2323 // reciprocal barrier to the MAP objective. The half-Student-t prior
2324 // supplies smooth regularisation inside the domain.
2325 scg_opt_settings.use_tail_lower_barrier = false;
2326 scg_opt_settings.tail_lower_barrier =
2327 -std::numeric_limits<double>::infinity();
2328
2329 // Refresh configured MAP prior parameters from the live SexpatCF hierarchy
2330 // when the opt-in flags are set (default off keeps weakly-informative
2331 // half-Cauchy / Student-t defaults identical to the built-in MAP priors).
2332 if (sexpat_cov_func != nullptr) {
2333 scg_opt_settings.map_use_lognormal_magn_prior =
2334 sexpat_cov_func->useLogNormalMagnPrior();
2335 if (scg_opt_settings.map_use_lognormal_magn_prior) {
2336 const PriorBase magn_p =
2337 sexpat_cov_func->getPriorParametersLogNormal();
2338 scg_opt_settings.map_magn_prior_mu = magn_p.getMu();
2339 scg_opt_settings.map_magn_prior_s2 = magn_p.getS2();
2340 scg_opt_settings.map_magn_prior_nu = magn_p.getNu();
2341 } else if (scg_opt_settings.map_use_configured_magn_prior) {
2342 const PriorBase magn_p = sexpat_cov_func->getPriorParametersSqrtt();
2343 scg_opt_settings.map_magn_prior_mu = magn_p.getMu();
2344 scg_opt_settings.map_magn_prior_s2 = magn_p.getS2();
2345 scg_opt_settings.map_magn_prior_nu = magn_p.getNu();
2346 }
2347 if (scg_opt_settings.map_use_configured_lengthscale_prior) {
2348 const PriorBase ls_p =
2349 sexpat_cov_func->getPriorParametersGaussian();
2350 scg_opt_settings.map_lengthscale_prior_mu = ls_p.getMu();
2351 scg_opt_settings.map_lengthscale_prior_s2 = ls_p.getS2();
2352 scg_opt_settings.map_lengthscale_prior_nu = ls_p.getNu();
2353 }
2354 }
2355
2356 auto optimizer_settings = scg_opt_settings;
2357 // Collective fits share one parameter sequence. Its trace belongs to
2358 // the model communicator's root, independently of the process count.
2359 if (backend().mpi().rank != 0) optimizer_settings.common.report_level = 0;
2360 std::visit(
2361 [&](auto& opt) {
2362 using OptType = std::decay_t<decltype(opt)>;
2363 if constexpr (kIsScgLike<OptType>) {
2364 auto settings = optimizer_settings;
2365 opt.setAlgorithmSettings(settings);
2366 }
2367#ifdef USE_CERES
2368 else if constexpr (std::is_same_v<OptType, funcmin::Ceres>) {
2369 opt.setAlgorithmSettings(ceres_opt_settings);
2370 }
2371#endif
2372 },
2373 optimizer_state_->optimizer);
2374
2375 if (this->report_level >= 2) {
2376 log_man << "Starting optimization with " << opt_R_matrix.rows()
2377 << " data points.\n";
2378 if (scg_opt_settings.use_tail_lower_barrier) {
2379 log_man << "Lengthscale lower barrier at exp("
2380 << scg_opt_settings.tail_lower_barrier
2381 << ") = " << std::exp(scg_opt_settings.tail_lower_barrier)
2382 << "\n";
2383 }
2384 }
2385
2386 double initial_strength = 1e-4;
2387 double growth_factor = 1e-3;
2388 double current_barrier_strength =
2389 initial_strength +
2390 growth_factor * gpr::coord::numPoints(opt_observation.R);
2391 auto start = std::chrono::steady_clock::now();
2392
2393 // Per-outer-iter training-kernel geometry handle. Built once here and
2394 // owned by a lexical objective holder so the inner-iter K assembly skips
2395 // dist_at + per-pair derivative recompute and applies theta to the
2396 // per-block unit-lengthscale geometry. The live evaluateEnergyAndGradient
2397 // callback handles inputs without a geometry representation, keeping
2398 // dispatch at the driver level.
2399 TrainingKernelGeometry training_geom;
2400 const bool training_geom_ready =
2401 canUseTrainingGeometryObjective() && use_training_geometry_handle_ &&
2402 prepareTrainingKernelGeometry(opt_R_matrix, opt_R_indices,
2403 training_geom, /*reused=*/true);
2404 const bool using_loo_objective =
2405 hyperparameter_objective_mode_ == HyperparameterObjectiveMode::LOO;
2406 // Unlike LOO, LOCAL_LOO does not need the training geometry handle
2407 // (every held-out geometry gets its own small dense solve), so it is
2408 // deliberately NOT part of the training_geom_ready hard-failure guard
2409 // below. It still needs to be excluded from the stationarity-skip
2410 // secant cache further down: that branch calls
2411 // evaluateEnergyAndGradientFromGeometry / evaluateEnergyAndGradient
2412 // directly rather than through this dispatch struct, and (for the
2413 // training_geom_ready path) the *FromGeometry variant is the NLML
2414 // one -- routing LOCAL_LOO through it there would silently cache a
2415 // secant built from the WRONG objective.
2416 const bool using_local_loo_objective =
2417 hyperparameter_objective_mode_ ==
2419 if (using_loo_objective && !training_geom_ready) {
2420 if (report_level >= 1) {
2421 log_man << "LOO hyperparameter objective requires the training "
2422 "geometry handle.\n";
2423 }
2424 failedOptimizer = true;
2425 // No objective can be evaluated: the all-rows fit is the only
2426 // remaining estimator.
2427 last_failed_fit_evaluable_ = false;
2428 leaveOptimizationObjectiveFrame(objective_frame, &parameters_cf);
2429 return old_parameters_cf;
2430 }
2431
2432 // Learned log(sigma2) is appended after the covariance parameters.
2433 // The signal anchor and the length-scale prior must not treat it as
2434 // another length scale.
2435 const Eigen::VectorXd kernel_parameters =
2436 parameters_cf.head(covariance_parameter_count);
2437 funcmin::MapObjectiveConfig map_objective_config =
2439 opt_R_matrix, opt_energy_and_gradient, kernel_parameters,
2440 current_barrier_strength, lengthscale_rho0, scg_opt_settings,
2441 hyperparameter_optimization_mode_ !=
2443 map_objective_config.lengthscale_count =
2444 std::max<Eigen::Index>(covariance_parameter_count - 1, 0);
2445 if (unregularized_marginal_likelihood_) {
2446 map_objective_config.barrier_strength = 0.0;
2447 map_objective_config.weight_mode = MapPriorWeightMode::Annealed;
2448 map_objective_config.use_magn_ceiling = false;
2449 map_objective_config.use_tail_lower_barrier = false;
2450 map_objective_config.use_configured_magn_prior = false;
2451 map_objective_config.use_lognormal_magn_prior = false;
2452 map_objective_config.use_configured_lengthscale_prior = false;
2453 }
2454 if (usesClassicJointEnergyForcePrior(model_profile_)) {
2455 // The model objective includes its complete log-parameter prior.
2456 // Optimizers preserve that density and the supplied parameter box.
2457 map_objective_config.barrier_strength = 0.0;
2458 map_objective_config.weight_mode = MapPriorWeightMode::Annealed;
2459 map_objective_config.use_magn_ceiling = false;
2460 map_objective_config.use_tail_lower_barrier = false;
2461 }
2462 map_objective_config.parameter_lower = parameter_lower;
2463 map_objective_config.parameter_upper = parameter_upper;
2464 // The tie structure: the leader of each group is its one parameter,
2465 // with the group's single prior; a member has no prior of its own and
2466 // keeps the general bounds and its place in the mask: the wrapped
2467 // objective gives it no gradient, so the optimizer never moves it,
2468 // while a masked-out member would lose its share of the group sum and
2469 // a degenerate box would stop the bounded optimizer short. Reapplied
2470 // when the review changes the structure.
2471 auto refresh_tie_structure = [&]() {
2472 if (!ties_active) return;
2473 const auto& ties = length_scale_ties_;
2474 // The mask is not touched: a member stays in it, since the
2475 // objective zeroes the gradient of a masked parameter before the
2476 // reduction sums a group; the member is held by its zero reduced
2477 // gradient instead.
2478 const bool masked = identifiable_mask.size() ==
2479 static_cast<std::size_t>(parameters_cf.size());
2480 map_objective_config.prior_weight =
2481 Eigen::VectorXd::Ones(parameters_cf.size());
2482 for (Index_t t = 0; t < ties.count(); ++t) {
2483 const Eigen::Index i = 1 + t;
2484 const auto index = static_cast<std::size_t>(i);
2485 const bool leader = ties.leader[static_cast<std::size_t>(t)] == t;
2486 const bool identified = !masked || identifiable_mask[index];
2487 map_objective_config.prior_weight(i) = leader ? 1.0 : 0.0;
2488 if (!leader || identified) {
2489 parameter_lower(i) = general_lower(i);
2490 parameter_upper(i) = general_upper(i);
2491 } else {
2492 parameter_lower(i) = parameters_cf(i);
2493 parameter_upper(i) = parameters_cf(i);
2494 }
2495 }
2496 map_objective_config.parameter_lower = parameter_lower;
2497 map_objective_config.parameter_upper = parameter_upper;
2498 };
2499 refresh_tie_structure();
2501 map_objective_config);
2502 // Log-parameter proposals use the configured prior's width. Unit width
2503 // is the factor-e scale of a log parameter without a configured prior.
2504 const double prior_s2 =
2505 scg_opt_settings.map_use_configured_lengthscale_prior
2506 ? scg_opt_settings.map_lengthscale_prior_s2
2507 : (sexpat_cov_func != nullptr
2508 ? sexpat_cov_func->getPriorParametersGaussian().getS2()
2509 : 0.0);
2510 const double parameter_search_halfwidth =
2511 std::isfinite(prior_s2) && prior_s2 > 0.0 ? std::sqrt(prior_s2) : 1.0;
2512 auto run_map_optimizer = [&](auto& optimizer, auto& objective,
2513 auto callback) {
2514 // The selected optimizer is rgmin. A stall falls back to rgmin L-BFGS.
2515 using Optimizer = std::decay_t<decltype(optimizer)>;
2516 // Each attempt reports its own SCG steps plus, when it falls
2517 // back, that fallback. A previous attempt's latch must not
2518 // attribute its L-BFGS steps to a later SCG-only refit.
2519 last_scg_fallback_used_ = false;
2520 optimizer_state_->last_fallback_rejected = false;
2521 scg_steps_before_fallback = 0;
2522 if constexpr (std::is_same_v<Optimizer, funcmin::RgminOpt>) {
2523 optimizer.setBox(parameter_lower, parameter_upper);
2524 optimizer.setPersistentSession(rgmin_warm_start_);
2525 optimizer.setInitialLogMove(rgmin_initial_log_move_);
2526 optimizer.setInitialLogMoveWholeSession(
2527 rgmin_initial_log_move_whole_session_);
2528 }
2529 const Eigen::VectorXd initial_parameters = parameters_cf;
2530 const int objective_count_before = PhaseTimers::objective_count;
2531 std::size_t rgmin_logical_work = 0;
2532 std::size_t rgmin_physical_work = 0;
2533 const auto retain_feasible_improvement = [&](bool failed) {
2534 // Diagnostics measure executed work. The anneal budget follows
2535 // the single-entry request policy for the local rgmin fit.
2536 last_fit_evaluations_ = static_cast<std::size_t>(std::max(
2537 0, PhaseTimers::objective_count - objective_count_before));
2538 last_fit_budget_evaluations_ =
2539 last_fit_evaluations_ -
2540 std::min(last_fit_evaluations_, rgmin_physical_work) +
2541 rgmin_logical_work;
2542 if (failed) surrogate_contradicted_ = true;
2543 if (scg_opt_settings.common.check_derivative &&
2544 parameters_cf.allFinite()) {
2545 const Eigen::VectorXd theta = parameters_cf;
2546 struct ObjectiveSample {
2547 double raw_value = 0.0;
2548 double map_value = 0.0;
2549 Eigen::VectorXd raw_gradient;
2550 Eigen::VectorXd map_gradient;
2551 };
2552 const auto sample = [&](const Eigen::VectorXd& point) {
2553 ObjectiveSample result;
2554 result.raw_gradient.resize(point.size());
2555 EnergyAndGradient eg(result.raw_value, result.raw_gradient);
2556 (objective.*callback)(point, opt_R_matrix, opt_R_indices,
2557 opt_energy_and_gradient, eg);
2558 result.map_value = result.raw_value;
2559 result.map_gradient = result.raw_gradient;
2560 funcmin::applyMapPenalty(point, map_objective_config,
2561 result.map_value,
2562 &result.map_gradient);
2563 return result;
2564 };
2565 const auto center = sample(theta);
2566 EigenMatrix audit_factor;
2567 if (!use_correction_ && !principled_nugget_ &&
2568 hyperparameter_objective_mode_ ==
2570#ifdef GPR_LINALG_SCALAPACK
2571 auto& state = backend().distributed();
2572 if (state.has_cached_L() &&
2573 state.cached_n() == opt_energy_and_gradient.size())
2574 audit_factor = state.gather(
2575 state.cached_L(), state.cached_L_desc(),
2576 state.cached_n(), state.cached_n(), true);
2577#else
2578 audit_factor = L;
2579#endif
2580 }
2581 Eigen::VectorXd audit_upper = parameter_upper;
2582 if (map_objective_config.use_magn_ceiling)
2583 audit_upper(0) =
2584 std::min(audit_upper(0),
2585 map_objective_config.max_log_magnSigma2);
2586 bool audit_root = true;
2587#ifdef GPR_LINALG_SCALAPACK
2588 audit_root = backend().distributed().is_root();
2589#endif
2590 if (audit_root && !use_correction_ && !principled_nugget_ &&
2591 hyperparameter_objective_mode_ ==
2593 EigenMatrix covariance;
2594 const bool cached_objective =
2595 hssvdObjectiveStampMatches() &&
2596 hssvd_objective_trace_via_cholesky_ &&
2597 hssvd_objective_pending_covariance_.rows() ==
2598 opt_energy_and_gradient.size();
2599 if (cached_objective) {
2600 covariance = hssvd_objective_pending_covariance_;
2601 if (!hssvd_objective_pending_permutation_.perm.empty())
2602 covariance = gpr::unpermuteSymmetricMatrix(
2603 covariance,
2604 hssvd_objective_pending_permutation_);
2605 } else {
2607 opt_R_matrix, opt_R_indices, covariance, true);
2608 covariance.diagonal().array() += jitter_sigma2;
2609 }
2610 log_man << "GP objective snapshot covariance: "
2611 << (cached_objective ? "active objective cache"
2612 : "independent assembly")
2613 << "\n";
2614 const double noise =
2615 lik_gaussian->getSigma2() + jitter_sigma2;
2616 const double constant = const_cov_fun->getConstSigma2();
2617 const double prior = -const_cov_fun->calculateLogPrior() -
2618 sexpat_cov_func->calculateLogPrior() -
2619 lik_gaussian->evaluateLogPrior();
2620 const FieldMatrixd prior_gradient =
2621 sexpat_cov_func->calculateLogPriorGradient();
2622 const double prior_amplitude_gradient =
2623 prior_gradient.size() ? -prior_gradient(0, 0) : 0.0;
2624 const std::uint64_t sizes[] = {
2625 static_cast<std::uint64_t>(covariance.rows()),
2626 static_cast<std::uint64_t>(opt_observation.E.size())};
2627 const double metadata[] = {noise,
2628 constant,
2629 center.raw_value,
2630 prior,
2631 center.raw_gradient(0),
2632 prior_amplitude_gradient};
2633 std::ofstream snapshot("gp-map-objective.bin",
2634 std::ios::binary);
2635 snapshot.write(reinterpret_cast<const char*>(sizes),
2636 sizeof(sizes));
2637 snapshot.write(reinterpret_cast<const char*>(metadata),
2638 sizeof(metadata));
2639 snapshot.write(
2640 reinterpret_cast<const char*>(covariance.data()),
2641 covariance.size() * sizeof(double));
2642 snapshot.write(
2643 reinterpret_cast<const char*>(
2644 opt_energy_and_gradient.data()),
2645 opt_energy_and_gradient.size() * sizeof(double));
2646 if (!snapshot)
2647 throw std::runtime_error(
2648 "cannot write GP objective covariance snapshot");
2649 if (cached_objective &&
2650 audit_factor.rows() == covariance.rows() &&
2651 b.size() == covariance.rows() &&
2652 hssvd_objective_alpha_.size() == covariance.rows()) {
2653 audit_factor
2654 .template triangularView<Eigen::StrictlyUpper>()
2655 .setZero();
2656 std::vector<std::int64_t> permutation(
2657 covariance.rows());
2658 for (Eigen::Index i = 0; i < covariance.rows(); ++i)
2659 permutation[i] = hasTrainingPermutation()
2660 ? training_permutation_.perm[i]
2661 : i;
2662 const std::uint64_t factor_header[] = {1, sizes[0]};
2663 std::ofstream factor_snapshot("gp-map-factor.bin",
2664 std::ios::binary);
2665 factor_snapshot.write(
2666 reinterpret_cast<const char*>(factor_header),
2667 sizeof(factor_header));
2668 factor_snapshot.write(
2669 reinterpret_cast<const char*>(permutation.data()),
2670 permutation.size() * sizeof(std::int64_t));
2671 for (const auto* matrix: {&audit_factor})
2672 factor_snapshot.write(
2673 reinterpret_cast<const char*>(matrix->data()),
2674 matrix->size() * sizeof(double));
2675 for (const auto* vector: {&b, &hssvd_objective_alpha_})
2676 factor_snapshot.write(
2677 reinterpret_cast<const char*>(vector->data()),
2678 vector->size() * sizeof(double));
2679 if (!factor_snapshot)
2680 throw std::runtime_error(
2681 "cannot write GP objective factor snapshot");
2682 }
2683 }
2684 for (Eigen::Index index = 0; index < theta.size(); ++index) {
2685 for (double step: {1e-2, 1e-3, 1e-4, 1e-5, 1e-6}) {
2686 Eigen::VectorXd first = theta, second = theta;
2687 double c1 = 0.0, c2 = 0.0;
2688 const char* stencil = nullptr;
2689 if (theta(index) - step >= parameter_lower(index) &&
2690 theta(index) + step < audit_upper(index)) {
2691 first(index) += step;
2692 second(index) -= step;
2693 c1 = 1.0;
2694 c2 = -1.0;
2695 stencil = "central";
2696 } else if (theta(index) + 2.0 * step <
2697 audit_upper(index)) {
2698 first(index) += step;
2699 second(index) += 2.0 * step;
2700 c1 = 4.0;
2701 c2 = -1.0;
2702 stencil = "forward";
2703 } else if (theta(index) - 2.0 * step >=
2704 parameter_lower(index)) {
2705 first(index) -= step;
2706 second(index) -= 2.0 * step;
2707 c1 = -4.0;
2708 c2 = 1.0;
2709 stencil = "backward";
2710 } else {
2711 continue;
2712 }
2713 const auto a = sample(first), b = sample(second);
2714 const double derivative =
2715 (c1 * (a.map_value - center.map_value) +
2716 c2 * (b.map_value - center.map_value)) /
2717 (2.0 * step);
2718 const double raw_derivative =
2719 (c1 * (a.raw_value - center.raw_value) +
2720 c2 * (b.raw_value - center.raw_value)) /
2721 (2.0 * step);
2722 std::fprintf(
2723 stderr,
2724 "[map-gradient] index=%lld step=%.17g "
2725 "stencil=%s theta=%.17g value=%.17g "
2726 "gradient=%.17g derivative=%.17g "
2727 "raw_gradient=%.17g raw_derivative=%.17g\n",
2728 static_cast<long long>(index), step, stencil,
2729 theta(index), center.map_value,
2730 center.map_gradient(index), derivative,
2731 center.raw_gradient(index), raw_derivative);
2732 }
2733 }
2734 // Restore the covariance and objective caches at the fitted
2735 // parameters so diagnostics preserve the model state.
2736 const auto repeated = sample(theta);
2737 if (audit_root)
2738 std::fprintf(
2739 stderr,
2740 "[map-gradient-repeat] value_delta=%.17g "
2741 "gradient_delta=%.17g\n",
2742 repeated.raw_value - center.raw_value,
2743 (repeated.raw_gradient - center.raw_gradient).norm());
2744 }
2745 if (!failed) return failed;
2746 const auto objective_value = [&](const Eigen::VectorXd& theta) {
2747 double value = 0.0;
2748 Eigen::VectorXd gradient(theta.size());
2749 EnergyAndGradient result(value, gradient);
2750 (objective.*callback)(theta, opt_R_matrix, opt_R_indices,
2751 opt_energy_and_gradient, result);
2752 funcmin::applyMapPenalty(theta, map_objective_config, value,
2753 &gradient);
2754 return gradient.allFinite() && std::isfinite(value)
2755 ? value
2756 : std::numeric_limits<double>::infinity();
2757 };
2758 // With no feasible fitted point the input theta is the only
2759 // candidate; probe it to record whether the marginal likelihood
2760 // is non-finite there, and when subset_failure_escalation_ is off
2761 // also record whether the penalized objective is evaluable.
2762 const auto note_input_evaluability = [&]() {
2763 double value = 0.0;
2764 Eigen::VectorXd gradient(initial_parameters.size());
2765 EnergyAndGradient result(value, gradient);
2766 (objective.*callback)(initial_parameters, opt_R_matrix,
2767 opt_R_indices, opt_energy_and_gradient,
2768 result);
2769 if (!std::isfinite(value))
2770 optimizer_state_->last_input_marginal_likelihood_nonfinite =
2771 true;
2773 initial_parameters, map_objective_config, value, &gradient);
2774 if (!subset_failure_escalation_)
2775 last_failed_fit_evaluable_ = std::isfinite(value);
2776 };
2777 if (!parameters_cf.allFinite()) {
2778 note_input_evaluability();
2779 return failed;
2780 }
2781 project_lengthscales_to_domain(parameters_cf);
2782 const double fitted_value = objective_value(parameters_cf);
2783 if (!std::isfinite(fitted_value)) {
2784 note_input_evaluability();
2785 return failed;
2786 }
2787 const double initial_value = objective_value(initial_parameters);
2788 last_failed_fit_improved_ = fitted_value < initial_value;
2789 if (last_failed_fit_improved_ && report_level >= 1) {
2790 log_man << "Feasible MAP objective decrease: " << initial_value
2791 << " -> " << fitted_value << ".\n";
2792 }
2793 return failed;
2794 };
2795#ifdef USE_ANNEAL
2796 // The global stage: on the first fit and every anneal_every_-th
2797 // fit after it, anneal's box ensemble searches the box around the
2798 // warm start and hands its best point to the local optimizer.
2799 // A restricted fit (an amplitude-only or active-subspace refit)
2800 // is not a search over the box: only a fit of every parameter
2801 // counts and runs the stage.
2802 const bool full_fit =
2803 scg_opt_settings.active_parameters.empty() ||
2804 std::all_of(scg_opt_settings.active_parameters.begin(),
2805 scg_opt_settings.active_parameters.end(),
2806 [](bool active) { return active; });
2807 if (anneal_enabled_ && full_fit)
2808 last_anneal_stage_.fits = ++anneal_fit_counter_;
2809 const bool stage_due =
2810 anneal_enabled_ && full_fit &&
2811 (anneal_every_ > 0
2812 ? (anneal_fit_counter_ - 1) % anneal_every_ == 0
2813 : anneal_fit_counter_ == 1 || surrogate_contradicted_);
2814 if (stage_due) {
2815 surrogate_contradicted_ = false;
2816 funcmin::AnnealStageSettings stage;
2817 Eigen::VectorXd anneal_lower = parameter_lower;
2818 Eigen::VectorXd anneal_upper = parameter_upper;
2819 if (ties_active) {
2820 // Only leaders parameterize the tied objective. Pinning its
2821 // redundant storage coordinates keeps the ensemble's box
2822 // distance and proposals in the independent subspace.
2823 for (Index_t t = 0; t < length_scale_ties_.count(); ++t) {
2824 if (length_scale_ties_.leader[t] == t) continue;
2825 anneal_lower(1 + t) = parameters_cf(1 + t);
2826 anneal_upper(1 + t) = parameters_cf(1 + t);
2827 }
2828 }
2829 const auto independent_parameters = static_cast<std::size_t>(
2830 (anneal_lower.array() < anneal_upper.array()).count());
2831 // The last local fit's work, with one opening evaluation and
2832 // one per independent parameter as the automatic minimum.
2833 stage.budget = anneal_budget_ > 0
2834 ? anneal_budget_
2835 : std::max(last_fit_budget_evaluations_,
2836 independent_parameters + 1);
2837 stage.replicas = anneal_replicas_;
2838 // The box: the length-scale prior's scale either way from the
2839 // warm start; a factor e when no prior scale is configured.
2840 stage.box_halfwidth = parameter_search_halfwidth;
2841 last_anneal_stage_.budget = stage.budget;
2842 last_anneal_stage_.box_halfwidth = stage.box_halfwidth;
2843 // The counter was advanced above: the first stage runs
2844 // with seed + 1, each later one with its own fit number.
2845 stage.seed = anneal_seed_ + anneal_fit_counter_;
2846 const auto report = funcmin::annealMapStage(
2847 opt_R_matrix, opt_R_indices, opt_energy_and_gradient,
2848 parameters_cf, objective, callback, map_objective_config,
2849 anneal_lower, anneal_upper, stage,
2850 optimizer_settings.common.report_level);
2851 last_anneal_stage_.ran = report.ran;
2852 last_anneal_stage_.failed = report.failed;
2853 last_anneal_stage_.improved = report.improved;
2854 // The stage's point is another basin: the previous fit's
2855 // quasi-Newton memory does not describe it.
2856 if (report.improved) forgetRgminSessions();
2857 last_anneal_stage_.start_value = report.start_value;
2858 last_anneal_stage_.value = report.value;
2859 last_anneal_stage_.evaluations = report.evaluations;
2860 last_anneal_stage_.gradients = report.gradients;
2861 last_anneal_stage_.hops = report.hops;
2862 if (report.ran) ++last_anneal_stage_.runs;
2863 if (report_level >= 1 && report.ran) {
2864 log_man << "Anneal stage: objective " << report.start_value
2865 << " -> " << report.value << " in "
2866 << report.evaluations << " evaluations, "
2867 << report.gradients << " gradients, " << report.hops
2868 << " hops"
2869 << (report.improved ? "; the local fit starts there"
2870 : "; the warm start stands")
2871 << ".\n";
2872 }
2873 }
2874#endif
2875 // The unchanged-subset skip may hold only a fit that met the
2876 // gradient tolerance: a step-size exit is not stationarity. Every
2877 // fit that ends without failing, including the rgmin retry after a
2878 // stalled SCG, reports the MAP gradient norm at its parameters.
2879 auto record_fit_gradient = [&]() {
2880 if (!skip_unchanged_subset_fit_ || !parameters_cf.allFinite())
2881 return;
2882 double value = 0.0;
2883 Eigen::VectorXd gradient(parameters_cf.size());
2884 EnergyAndGradient result(value, gradient);
2885 (objective.*callback)(parameters_cf, opt_R_matrix, opt_R_indices,
2886 opt_energy_and_gradient, result);
2887 funcmin::applyMapPenalty(parameters_cf, map_objective_config, value,
2888 &gradient);
2889 funcmin::projectMapGradient(map_objective_config, gradient);
2890 if (std::isfinite(value) && gradient.allFinite())
2891 last_fit_gradient_norm_ = gradient.norm();
2892 };
2893 // The MAP fit is judged by its gradient. SCG stops on its own step
2894 // and objective-change test with that gradient orders of magnitude
2895 // above the tolerance on every outer of a large cell (11_grignard:
2896 // 0.4 against 0.001, 55 of 53 outers), and the rgmin L-BFGS retry
2897 // then does the fit. A stall is remembered: from then on the fit
2898 // starts with L-BFGS and the stalled optimizer is not run again,
2899 // which removes the wasted half of the refit wall (measured 5.6 s
2900 // against 13.2 s per outer on 17_oxycope).
2901 bool rejected_nonimproving_fallback = false;
2902 auto run_alternative = [&](double gradient_tolerance) {
2903 rejected_nonimproving_fallback = false;
2904 optimizer_state_->last_fallback_rejected = false;
2905 const Eigen::VectorXd scg_point = parameters_cf;
2906 const bool scg_point_feasible =
2907 scg_point.allFinite() &&
2908 (scg_point.array() >= parameter_lower.array()).all() &&
2909 (scg_point.array() <= parameter_upper.array()).all();
2910 const auto map_value = [&](const Eigen::VectorXd& point) {
2911 double value = 0.0;
2912 Eigen::VectorXd gradient(point.size());
2913 EnergyAndGradient result(value, gradient);
2914 (objective.*callback)(point, opt_R_matrix, opt_R_indices,
2915 opt_energy_and_gradient, result);
2916 funcmin::applyMapPenalty(point, map_objective_config, value,
2917 &gradient);
2918 return std::isfinite(value)
2919 ? value
2920 : std::numeric_limits<double>::infinity();
2921 };
2922 last_scg_fallback_used_ = true;
2923 funcmin::RgminOpt& alternative = optimizer_state_->scg_alternative;
2924 alternative.setPersistentSession(rgmin_warm_start_);
2925 alternative.setAlgorithmSettings(optimizer_settings);
2926 alternative.setMethod(RGMIN_LBFGS);
2927 alternative.setGradTol(gradient_tolerance);
2928 alternative.setBox(parameter_lower, parameter_upper);
2929 double lbfgs_opening_value =
2930 std::numeric_limits<double>::quiet_NaN();
2931 double lbfgs_last_value = std::numeric_limits<double>::quiet_NaN();
2932 alternative.optimizeWithObjectiveValues(
2933 opt_R_matrix, opt_R_indices, opt_energy_and_gradient,
2934 parameters_cf, callback, objective, current_barrier_strength,
2935 lengthscale_rho0, &map_objective_config, &lbfgs_opening_value,
2936 &lbfgs_last_value);
2937 rgmin_logical_work += alternative.logicalObjectiveWork();
2938 rgmin_physical_work += alternative.physicalObjectiveWork();
2939 if (alternative.failedOptim && report_level >= 2) {
2940 log_man << "Failed rgmin MAP parameters: "
2941 << parameters_cf.transpose() << "\n";
2942 }
2943 // A dimer search asks to keep L-BFGS only when it lowers the
2944 // MAP objective by more than the absolute tolerance
2945 // improvement_tol (1e-3 in objective units, not a ratio). Both
2946 // values are the ones this fit already computed: scoring them again
2947 // leaves the factor off the point L-BFGS restored. Only a rejection
2948 // restores a feasible SCG point and rebuilds the factor there.
2949 if (optimizer_state_->require_scg_fallback_improvement &&
2950 !alternative.failedOptim && scg_point_feasible) {
2951 const double lbfgs_value = lbfgs_last_value;
2952 const double scg_value = lbfgs_opening_value;
2953 const bool comparable =
2954 std::isfinite(lbfgs_value) && std::isfinite(scg_value);
2955 const double improvement_tol = 1.0e-3;
2956 if (comparable &&
2957 !(lbfgs_value < scg_value - improvement_tol)) {
2958 parameters_cf = scg_point;
2959 (void)map_value(parameters_cf);
2960 rejected_nonimproving_fallback = true;
2961 optimizer_state_->last_fallback_rejected = true;
2962 last_scg_fallback_used_ = false;
2963 }
2964 }
2965 if (!alternative.failedOptim && !rejected_nonimproving_fallback) {
2966 record_fit_gradient();
2967 }
2968 return retain_feasible_improvement(alternative.failedOptim ||
2969 rejected_nonimproving_fallback);
2970 };
2971 const auto drop_rejected_stall = [&]() {
2972 if (!rejected_nonimproving_fallback) return;
2973 scg_stalled_ = false;
2974 scg_stall_scope_ = {};
2975 };
2976 const auto scg_dim = static_cast<std::size_t>(parameters_cf.size());
2977 const ScgStallScope current_scg_scope{
2978 scg_dim,
2979 map_objective_config.active_parameters.empty()
2980 ? std::vector<bool>(scg_dim, true)
2981 : map_objective_config.active_parameters,
2982 hyperparameter_objective_mode_,
2983 model_profile_,
2984 unregularized_marginal_likelihood_,
2985 lik_gaussian != nullptr && lik_gaussian->getOptimizeSigma2(),
2986 disable_output_normalization_,
2987 zblPriorMeanActive() && !ffPriorMeanActive(),
2988 ffPriorMeanActive(),
2990 ties_active,
2991 ties_active ? length_scale_ties_.released : std::vector<bool>{}};
2992 if constexpr (kUsesScg<Optimizer>) {
2993 if (scg_stalled_ && scg_stall_scope_ != current_scg_scope) {
2994 scg_stalled_ = false;
2995 scg_stall_scope_ = {};
2996 }
2997 if (scg_stalled_) {
2998 const bool failed = run_alternative(
2999 std::min(scg_opt_settings.common.tolerance_func,
3000 scg_opt_settings.common.tolerance_sol));
3001 drop_rejected_stall();
3002 return failed;
3003 }
3004 }
3005 optimizer.optimize(opt_R_matrix, opt_R_indices, opt_energy_and_gradient,
3006 parameters_cf, callback, objective,
3007 current_barrier_strength, lengthscale_rho0,
3008 &map_objective_config);
3009 if constexpr (kUsesScg<Optimizer>) {
3010 if (optimizer.hessianVectorFallback) {
3011 noteNlmlHessianVectorFallback(
3012 "the MAP optimizer",
3013 "the exact NLML Hessian-vector product was unavailable or "
3014 "failed during the fit");
3015 }
3016 }
3017 if constexpr (std::is_same_v<Optimizer, funcmin::RgminOpt>) {
3018 rgmin_logical_work += optimizer.logicalObjectiveWork();
3019 rgmin_physical_work += optimizer.physicalObjectiveWork();
3020 }
3021 if constexpr (kUsesScg<Optimizer>) {
3022 const double gradient_tolerance =
3023 std::min(scg_opt_settings.common.tolerance_func,
3024 scg_opt_settings.common.tolerance_sol);
3025 bool needs_alternative =
3026 optimizer.failedOptim || !parameters_cf.allFinite() ||
3027 (parameters_cf.array() < parameter_lower.array()).any() ||
3028 (parameters_cf.array() > parameter_upper.array()).any();
3029 if (!needs_alternative) {
3030 double value = 0.0;
3031 Eigen::VectorXd gradient(parameters_cf.size());
3032 EnergyAndGradient result(value, gradient);
3033 (objective.*callback)(parameters_cf, opt_R_matrix,
3034 opt_R_indices, opt_energy_and_gradient,
3035 result);
3036 funcmin::applyMapPenalty(parameters_cf, map_objective_config,
3037 value, &gradient);
3038 funcmin::projectMapGradient(map_objective_config, gradient);
3039 needs_alternative = !std::isfinite(value) ||
3040 !gradient.allFinite() ||
3041 gradient.norm() > gradient_tolerance;
3042 if (needs_alternative && report_level >= 1) {
3043 log_man << "SCG stopped with MAP gradient norm "
3044 << gradient.norm() << " above tolerance "
3045 << gradient_tolerance << ".\n";
3046 }
3047 }
3048 if (needs_alternative) {
3049 // A requested iteration limit does not establish a solver
3050 // stall or change the optimizer sequence of later fits.
3051 // The steps SCG already took belong to this fit even
3052 // though L-BFGS finishes it.
3053 scg_steps_before_fallback = optimizer.completedIterations;
3054 if (!optimizer.exhaustedIterationBudget) {
3055 scg_stalled_ = true;
3056 scg_stall_scope_ = current_scg_scope;
3057 }
3058 if (report_level >= 2) {
3059 log_man
3060 << "MAP input parameters: "
3061 << initial_parameters.transpose()
3062 << "\nSCG returned parameters: "
3063 << parameters_cf.transpose()
3064 << "\nMAP lower bounds: " << parameter_lower.transpose()
3065 << "\nMAP upper bounds: " << parameter_upper.transpose()
3066 << "\n";
3067 }
3068 if (report_level >= 1) {
3069 log_man << "SCG did not converge; retrying the MAP fit "
3070 "with rgmin L-BFGS.\n";
3071 }
3072 const bool failed = run_alternative(gradient_tolerance);
3073 drop_rejected_stall();
3074 return failed;
3075 }
3076 }
3077 if (!optimizer.failedOptim) record_fit_gradient();
3078 return retain_feasible_improvement(optimizer.failedOptim);
3079 };
3080
3081 auto optimize_objective = [&](auto& objective) {
3082 using Objective = std::decay_t<decltype(objective)>;
3083 const auto callback = &Objective::evaluateEnergyAndGradient;
3084 std::visit(
3085 [&](auto& optimizer) {
3086 using Optimizer = std::decay_t<decltype(optimizer)>;
3087 if constexpr (kIsScgLike<Optimizer>) {
3088 failedOptimizer =
3089 run_map_optimizer(optimizer, objective, callback);
3090 } else {
3091 optimizer.optimize(opt_R_matrix, opt_R_indices,
3092 opt_energy_and_gradient, parameters_cf,
3093 callback, objective,
3094 current_barrier_strength);
3095 failedOptimizer = optimizer.failedOptim;
3096 if (failedOptimizer && !subset_failure_escalation_) {
3097 double value = 0.0;
3098 Eigen::VectorXd gradient(parameters_cf.size());
3099 EnergyAndGradient result(value, gradient);
3100 (objective.*callback)(parameters_cf, opt_R_matrix,
3101 opt_R_indices,
3102 opt_energy_and_gradient, result);
3103 last_failed_fit_evaluable_ =
3104 std::isfinite(value) && gradient.allFinite();
3105 }
3106 }
3107 },
3108 optimizer_state_->optimizer);
3109 };
3110 if (report_level >= 1) {
3111 log_man << "GP parameter optimizer: "
3112 << hyperparameterOptimizationModeName()
3113 << " backend=" << getHyperparameterOptimizerBackend();
3114 if (ties_active)
3115 log_man << " tied length scales="
3116 << length_scale_ties_.count() -
3117 std::count(length_scale_ties_.released.begin(),
3118 length_scale_ties_.released.end(), true);
3119 log_man << "\n";
3120 }
3121 // Release tied length scales on accumulated evidence. Releases are
3122 // monotone: a released scale stays its own. Each fit screens the tied
3123 // members by the quadratic model along their own coordinate, g^2/(2h)
3124 // against the Occam cost of one parameter, half the log of the row
3125 // count. The curvatures h come from Hutchinson's diagonal estimator
3126 // (Bekas, Kokiopoulou and Saad 2007): gradient differences along
3127 // random sign vectors over the candidate coordinates, taken one at a
3128 // time until every candidate is settled to one standard error or the
3129 // candidates still ambiguous number no more than the probes spent, at
3130 // which point those are probed exactly. The screened set is released
3131 // in a trial refit, the realized change of the negative log marginal
3132 // likelihood is attributed to the candidates in proportion to their
3133 // predicted gains, and each candidate's share less the Occam cost
3134 // feeds its cumulative sum (Page 1954), floored at zero; a candidate
3135 // whose sum reaches the Occam cost is released, the others return to
3136 // their groups. Evidence from one subset fit that falls short is thus
3137 // kept, and a marginal scale is released only once several fits agree.
3138 auto review_length_scale_ties = [&](auto& objective, auto callback) {
3139 if (!ties_active || failedOptimizer) return;
3140 const auto t0 = std::chrono::steady_clock::now();
3141 auto& ties = length_scale_ties_;
3142 if (ties.evidence.size() != ties.parent.size())
3143 ties.evidence.assign(ties.parent.size(), 0.0);
3144 // The objective's energy carries the covariance function's own
3145 // prior, whose terms change with the tie structure (a released
3146 // type gains one); the evidence compares likelihoods, so that
3147 // prior is added back at the evaluated point.
3148 const auto evaluate = [&](const Eigen::VectorXd& point, double& nlml,
3149 Eigen::VectorXd& gradient) {
3150 nlml = 0.0;
3151 gradient = Eigen::VectorXd::Zero(point.size());
3152 EnergyAndGradient eg(nlml, gradient);
3153 (objective.*callback)(point, opt_R_matrix, opt_R_indices,
3154 opt_energy_and_gradient, eg);
3155 if (sexpat_cov_func != nullptr && std::isfinite(nlml))
3156 nlml += sexpat_cov_func->calculateLogPrior();
3157 double penalised = nlml;
3158 funcmin::applyMapPenalty(point, map_objective_config, penalised,
3159 &gradient);
3160 return std::isfinite(nlml) && gradient.size() == point.size() &&
3161 gradient.allFinite();
3162 };
3163 const double occam =
3164 0.5 * std::log(static_cast<double>(opt_energy_and_gradient.size()));
3165 double nlml0 = 0.0;
3166 Eigen::VectorXd base;
3167 if (!evaluate(parameters_cf, nlml0, base)) return;
3168 const double step = std::cbrt(std::numeric_limits<double>::epsilon());
3169 // Candidates: tied members the data identify.
3170 std::vector<Index_t> candidates;
3171 for (Index_t t = 0; t < ties.count(); ++t) {
3172 const auto index = static_cast<std::size_t>(t);
3173 if (ties.released[index] || ties.leader[index] == t) continue;
3174 const auto p = static_cast<std::size_t>(1 + t);
3175 if (scg_opt_settings.active_parameters.size() ==
3176 static_cast<std::size_t>(parameters_cf.size()) &&
3177 !scg_opt_settings.active_parameters[p])
3178 continue;
3179 candidates.push_back(t);
3180 }
3181 if (candidates.empty()) return;
3182 // The quadratic is local to the same prior-width neighborhood used
3183 // for hyperparameter exploration, intersected with the fit domain.
3184 const auto lower_step = [&](Index_t p) {
3185 return std::max(parameter_lower(p) - parameters_cf(p),
3186 -parameter_search_halfwidth);
3187 };
3188 const auto upper_step = [&](Index_t p) {
3189 return std::min(parameter_upper(p) - parameters_cf(p),
3190 parameter_search_halfwidth);
3191 };
3192 const auto gain_at = [&](Index_t t, double curvature) {
3193 const auto p = 1 + t;
3194 return detail::quadraticEvidenceGain(base(p), curvature,
3195 lower_step(p), upper_step(p));
3196 };
3197 // Curvature and gain belong to this likelihood at this parameter
3198 // vector. Changed training rows require their own screening probes.
3199 // Hutchinson diagonal over the candidate coordinates.
3200 const std::size_t count = candidates.size();
3201 std::vector<double> sum(count, 0.0), sum_sq(count, 0.0);
3202 std::vector<int> settled(count, 0); // 1 pass, -1 fail, 0 ambiguous
3203 std::vector<double> curvature(count, 0.0);
3204 int probes = 0;
3205 std::mt19937_64 signs(static_cast<std::uint64_t>(
3206 opt_energy_and_gradient.size() + ties.count()));
3207 // Under nlml_hessian_vector the product is exact at the factor the
3208 // base evaluate() built. Without the product, or from the first
3209 // product that fails, the screen takes the one-sided differences of
3210 // finite_difference.
3211 bool hessian_vector_probes = nlmlHessianVectorCurvatureRequested();
3212 if (hessian_vector_probes &&
3214 hessian_vector_probes = false;
3215 noteNlmlHessianVectorFallback(
3216 "the length-scale tie screen",
3217 "the objective has no exact NLML Hessian-vector product");
3218 }
3219 const auto probe_along = [&](const Eigen::VectorXd& direction,
3220 Eigen::VectorXd& hv) {
3221 if (hessian_vector_probes) {
3222 ++probes;
3224 objective, opt_R_indices, opt_R_matrix,
3225 opt_energy_and_gradient, direction, hv)) {
3226 funcmin::mapPenaltyHessianVector(parameters_cf, direction,
3227 map_objective_config, hv);
3228 if (hv.allFinite()) return true;
3229 }
3230 --probes;
3231 hessian_vector_probes = false;
3232 noteNlmlHessianVectorFallback(
3233 "the length-scale tie screen",
3234 "the exact NLML Hessian-vector product failed");
3235 }
3236 Eigen::VectorXd point = parameters_cf + step * direction;
3237 double nlml_probe = 0.0;
3238 Eigen::VectorXd shifted;
3239 ++probes;
3240 if (!evaluate(point, nlml_probe, shifted)) return false;
3241 hv = (shifted - base) / step;
3242 return true;
3243 };
3244 bool stochastic = count > 2;
3245 if (stochastic) {
3246 std::vector<int> z(count, 1);
3247 for (std::size_t i = 1; i <= count; ++i) {
3248 for (std::size_t c = 0; c < count; ++c)
3249 z[c] = (signs() & 1U) ? 1 : -1;
3250 Eigen::VectorXd direction =
3251 Eigen::VectorXd::Zero(parameters_cf.size());
3252 for (std::size_t c = 0; c < count; ++c)
3253 direction(1 + candidates[c]) = z[c];
3254 Eigen::VectorXd hv;
3255 if (!probe_along(direction, hv)) {
3256 stochastic = false;
3257 break;
3258 }
3259 for (std::size_t c = 0; c < count; ++c) {
3260 const double d = z[c] * hv(1 + candidates[c]);
3261 sum[c] += d;
3262 sum_sq[c] += d * d;
3263 }
3264 if (i < 2) continue;
3265 std::size_t ambiguous = 0;
3266 for (std::size_t c = 0; c < count; ++c) {
3267 const double mean = sum[c] / static_cast<double>(i);
3268 const double variance = std::max(
3269 0.0, sum_sq[c] / static_cast<double>(i) - mean * mean);
3270 const double error =
3271 std::sqrt(variance / static_cast<double>(i - 1));
3272 const double low = mean - error, high = mean + error;
3273 const auto p = 1 + candidates[c];
3274 settled[c] =
3275 static_cast<int>(detail::screenQuadraticEvidence(
3276 base(p), low, high, occam, lower_step(p),
3277 upper_step(p)));
3278 curvature[c] = mean;
3279 if (settled[c] == 0) ++ambiguous;
3280 }
3281 if (ambiguous == 0 || ambiguous <= i) break;
3282 }
3283 }
3284 // Exact probes for the ambiguous candidates, or for all of them
3285 // when the stochastic screen was not used.
3286 for (std::size_t c = 0; c < count; ++c) {
3287 if (stochastic && settled[c] != 0) continue;
3288 Eigen::VectorXd direction =
3289 Eigen::VectorXd::Zero(parameters_cf.size());
3290 direction(1 + candidates[c]) = 1.0;
3291 Eigen::VectorXd hv;
3292 if (!probe_along(direction, hv)) {
3293 settled[c] = -1;
3294 continue;
3295 }
3296 curvature[c] = hv(1 + candidates[c]);
3297 settled[c] = gain_at(candidates[c], curvature[c]) > occam ? 1 : -1;
3298 }
3299 last_tie_screen_probes_ = probes;
3300 last_tie_screen_hessian_vector_ = hessian_vector_probes;
3301 last_tie_screen_curvatures_ = curvature;
3302 std::vector<Index_t> screened;
3303 std::vector<double> predicted;
3304 for (std::size_t c = 0; c < count; ++c) {
3305 if (settled[c] != 1) continue;
3306 screened.push_back(candidates[c]);
3307 predicted.push_back(gain_at(candidates[c], curvature[c]));
3308 }
3309 int released_now = 0;
3310 if (!screened.empty()) {
3311 // Trial release of the screened set.
3312 const std::vector<bool> released_before = ties.released;
3313 const Eigen::VectorXd parameters_before = parameters_cf;
3314 const Eigen::VectorXd prior_weight_before =
3315 map_objective_config.prior_weight;
3316 const auto mask_before = scg_opt_settings.active_parameters;
3317 const Eigen::VectorXd lower_before = parameter_lower;
3318 const Eigen::VectorXd upper_before = parameter_upper;
3319 for (const Index_t t: screened)
3320 ties.released[static_cast<std::size_t>(t)] = true;
3321 refreshLengthScaleLeaders();
3322 refresh_tie_structure();
3323 detail::TiedLengthScaleObjective<std::decay_t<decltype(objective)>>
3324 tied{objective, *this};
3325 optimize_objective(tied);
3326 tieLengthScaleParameters(parameters_cf);
3327 double nlml_after = 0.0;
3328 Eigen::VectorXd gradient_after;
3329 const bool ok = !failedOptimizer &&
3330 evaluate(parameters_cf, nlml_after, gradient_after);
3331 const double change = ok ? nlml0 - nlml_after : 0.0;
3332 double predicted_total = 0.0;
3333 for (const double g: predicted)
3334 predicted_total += g;
3335 std::vector<Index_t> keep;
3336 for (std::size_t k = 0; k < screened.size(); ++k) {
3337 const auto index = static_cast<std::size_t>(screened[k]);
3338 const double share =
3339 predicted_total > 0.0
3340 ? change * predicted[k] / predicted_total
3341 : change / static_cast<double>(screened.size());
3342 double& evidence = ties.evidence[index];
3343 evidence =
3344 ok ? std::max(0.0, evidence + share - occam) : evidence;
3345 if (ok && evidence >= occam) keep.push_back(screened[k]);
3346 }
3347 if (report_level >= 1) {
3348 log_man << "Length-scale ties: trial release of "
3349 << screened.size() << " pair type(s)";
3350 for (std::size_t k = 0; k < screened.size(); ++k)
3351 log_man
3352 << " " << screened[k] << "/"
3353 << ties.parent[static_cast<std::size_t>(screened[k])]
3354 << "("
3355 << ties.evidence[static_cast<std::size_t>(screened[k])]
3356 << ")";
3357 log_man << (ok ? " changed the objective by " : " failed; ")
3358 << (ok ? std::to_string(change) : std::string())
3359 << " against " << occam
3360 << " per parameter: " << keep.size() << " released.\n";
3361 }
3362 if (keep.size() == screened.size() && ok) {
3363 released_now = static_cast<int>(keep.size());
3364 } else {
3365 // Return the others to their groups; a kept release keeps
3366 // its fitted scale, the next fit refines the rest.
3367 ties.released = released_before;
3368 for (const Index_t t: keep)
3369 ties.released[static_cast<std::size_t>(t)] = true;
3370 refreshLengthScaleLeaders();
3371 if (keep.empty()) {
3372 parameters_cf = parameters_before;
3373 map_objective_config.prior_weight = prior_weight_before;
3374 scg_opt_settings.active_parameters = mask_before;
3375 parameter_lower = lower_before;
3376 parameter_upper = upper_before;
3377 map_objective_config.parameter_lower = parameter_lower;
3378 map_objective_config.parameter_upper = parameter_upper;
3379 } else {
3380 refresh_tie_structure();
3381 tieLengthScaleParameters(parameters_cf);
3382 }
3383 released_now = static_cast<int>(keep.size());
3384 failedOptimizer = false;
3385 }
3386 }
3387 if (report_level >= 1 && (probes > 0 || released_now > 0)) {
3388 log_man << "Length-scale ties: " << probes << " probes ("
3389 << (stochastic ? "stochastic" : "exact") << "), "
3390 << screened.size() << " screened, " << released_now
3391 << " released, "
3392 << std::count(ties.released.begin(), ties.released.end(),
3393 true)
3394 << "/" << ties.count() << " own scales, occam " << occam
3395 << ", "
3396 << std::chrono::duration<double>(
3397 std::chrono::steady_clock::now() - t0)
3398 .count()
3399 << " s.\n";
3400 }
3401 };
3402 auto optimize_with_ties = [&](auto& objective) {
3403 using Objective = std::decay_t<decltype(objective)>;
3404 if (ties_active) {
3405 detail::TiedLengthScaleObjective<Objective> tied{objective, *this};
3406 optimize_objective(tied);
3407 // The optimizer's iterate is the tied point up to the per-index
3408 // domain clamps; restate the ties before reading it.
3409 tieLengthScaleParameters(parameters_cf);
3410 review_length_scale_ties(objective,
3411 &Objective::evaluateEnergyAndGradient);
3412 } else {
3413 optimize_objective(objective);
3414 }
3415 };
3416 if (training_geom_ready) {
3417#ifdef GPR_LINALG_SCALAPACK
3418 auto& st = backend().distributed();
3419 st.initialize();
3420 if (st.nprocs() > 1) {
3421 CanonicalDistributedMapObjective objective{*this, training_geom};
3422 optimize_with_ties(objective);
3423 } else
3424#endif
3425 {
3426 TrainingGeometryObjective objective{*this, training_geom};
3427 optimize_with_ties(objective);
3428 }
3429 } else {
3430 optimize_with_ties(*this);
3431 }
3432
3433 last_scg_exhausted_iteration_budget_ = false;
3434 last_fit_iterations_ = 0;
3435 last_fit_restarts_ = 0;
3436 last_fit_stop_reason_ = "unset";
3437 if (last_scg_fallback_used_) {
3438 const auto& alt = optimizer_state_->scg_alternative;
3439 last_scg_exhausted_iteration_budget_ = alt.exhaustedIterationBudget;
3440 last_fit_iterations_ =
3441 scg_steps_before_fallback + alt.completedIterations;
3442 last_fit_stop_reason_ =
3443 alt.exhaustedIterationBudget ? "budget" : "library";
3444 } else {
3445 std::visit(
3446 [&](auto& _popt) {
3447 using OptType = std::decay_t<decltype(_popt)>;
3448 if constexpr (std::is_same_v<OptType, funcmin::RgminScg> ||
3449 std::is_same_v<OptType, funcmin::RgminOpt>) {
3450 last_scg_exhausted_iteration_budget_ =
3451 _popt.exhaustedIterationBudget;
3452 last_fit_iterations_ = _popt.completedIterations;
3453 last_fit_stop_reason_ =
3454 _popt.exhaustedIterationBudget ? "budget" : "library";
3455 }
3456 },
3457 optimizer_state_->optimizer);
3458 }
3459 if (optimizer_state_->last_fallback_rejected) {
3460 last_fit_stop_reason_ = "restored scg point";
3461 }
3462
3463 project_lengthscales_to_domain(parameters_cf);
3464
3465 const double skip_scg_threshold =
3466 objectiveStationaritySkipThreshold(parameters_cf);
3467 if (!failedOptimizer && !using_loo_objective &&
3468 !using_local_loo_objective && skip_scg_threshold > 0.0) {
3469 bool stationarity_cache_ready = false;
3470 const bool use_bb_stationarity =
3471 use_hssvd_backend_ && objective_stationarity_bb_valid_;
3472 // Automatic checks reuse optimizer curvature or evaluate a directional
3473 // secant when observations change. A dense Hessian costs quadratically
3474 // many directional probes as environment-specific length scales grow.
3475 const bool explicit_stationarity_hessian =
3476 laplace_skip_scg_threshold_ > 0.0 &&
3477 std::isfinite(laplace_skip_scg_threshold_);
3478 if (!stationarity_cache_ready && !use_bb_stationarity &&
3479 explicit_stationarity_hessian) {
3480 stationarity_cache_ready = cacheObjectiveStationarityHessian(
3481 opt_R_indices, opt_R_matrix, opt_energy_and_gradient,
3482 parameters_cf);
3483 }
3484 if (!stationarity_cache_ready && !use_bb_stationarity) {
3485 invalidateObjectiveStationarityHessian();
3486 }
3487 } else if (failedOptimizer) {
3488 invalidateObjectiveStationarityHessian();
3489 }
3490
3491 if (this->report_level >= 2) {
3492 auto elp_time = (std::chrono::steady_clock::now() - start);
3493 auto elp_seconds =
3494 std::chrono::duration_cast<std::chrono::duration<double>>(elp_time);
3495
3496 log_man << "Optimization finished in: " << elp_seconds.count()
3497 << "s. Success: " << !failedOptimizer << "\n";
3498 log_man << "Parameter change norm: "
3499 << (old_parameters_cf - parameters_cf).norm() << "\n";
3500 }
3501
3502 captureFittedHyperparameterDensity(
3503 opt_observation.R, opt_energy_and_gradient, parameters_cf,
3504 map_objective_config, objective_frame.target_scale, true);
3505 leaveOptimizationObjectiveFrame(objective_frame, &parameters_cf);
3506 return parameters_cf;
3507}
void setPersistentSession(bool keep) noexcept
Definition RgminOpt.h:154
void setAlgorithmSettings(const gpr::ScgOptimizationSettings &s)
Definition RgminOpt.h:44
std::size_t logicalObjectiveWork() const noexcept
Objective-count units for the fit under a single-entry request cache.
Definition RgminOpt.h:204
void setMethod(rgmin::Method m) noexcept
Definition RgminOpt.h:49
std::size_t physicalObjectiveWork() const noexcept
Executed objective-count units, including final holder restoration.
Definition RgminOpt.h:209
void optimizeWithObjectiveValues(const gpr::EigenMatrix &x, const Eigen::VectorXd &x_ind, const Eigen::VectorXd &y, Eigen::VectorXd &w, FuncName func_to_min, ClassName &holder, double barrier_strength, const Eigen::VectorXd &lengthscale_rho0, const MapObjectiveConfig *objective_config, double *opening_value_out, double *last_value_out)
Definition RgminOpt.inl:31
void setBox(Eigen::VectorXd lower, Eigen::VectorXd upper)
Coordinate box on x + p. Empty is unbounded on that side.
Definition RgminOpt.h:136
void setGradTol(double g) noexcept
Definition RgminOpt.h:130
void poolDescriptorScaleByTies(Eigen::VectorXd &scales) const
OptimizationObjectiveFrame enterOptimizationObjectiveFrame(Eigen::VectorXd &targets, Eigen::Index energy_count, Eigen::VectorXd *theta)
void leaveOptimizationObjectiveFrame(const OptimizationObjectiveFrame &frame, Eigen::VectorXd *theta) noexcept
bool nlmlHessianVectorCurvatureRequested() const noexcept
void noteNlmlHessianVectorFallback(const char *where, const char *why)
Definition Hessian.cpp:361
void restoreMapAmplitudeFeasibility(Eigen::VectorXd &w, const MapObjectiveConfig &cfg)
MapObjectiveConfig makeMapObjectiveConfig(const gpr::EigenMatrix &x, const Eigen::VectorXd &y, const Eigen::VectorXd &w, double current_barrier_strength, const Eigen::VectorXd &lengthscale_rho0, const gpr::ScgOptimizationSettings &settings, bool robust_signal_anchor=true)
bool holderHasNlmlHessianVector(Holder &holder)
void applyMapPenalty(const Eigen::VectorXd &w, const MapObjectiveConfig &cfg, double &energy, Eigen::VectorXd *gradient)
void mapPenaltyHessianVector(const Eigen::VectorXd &w, const Eigen::VectorXd &direction, const MapObjectiveConfig &cfg, Eigen::VectorXd &product)
void projectMapGradient(const MapObjectiveConfig &cfg, Eigen::VectorXd &gradient)
bool holderNlmlHessianVector(Holder &holder, const Eigen::VectorXd &x_ind, const gpr::EigenMatrix &x, const Eigen::VectorXd &y, const Eigen::VectorXd &direction, Eigen::VectorXd &product)
Index_t numPoints(const FieldMatrixd &mat)
VecchiaResult evaluate(const Eigen::MatrixXd &points, const Eigen::VectorXd &y, double lengthscale, double noise, int max_neighbours)
double lengthscaleProjectionFloor(double max_pair_distance, double absolute_floor)
Eigen::VectorXd prior_weight

◆ permuteTrainingRows()

EigenMatrix gpr::GaussianProcessRegression::permuteTrainingRows ( const EigenMatrix & input) const
nodiscardprotected

Definition at line 610 of file GaussianProcessRegression.cpp.

612{
613 if (!hasTrainingPermutation()) return input;
615}

◆ permuteTrainingVector()

Eigen::VectorXd gpr::GaussianProcessRegression::permuteTrainingVector ( const Eigen::VectorXd & input) const
nodiscardprotected

Definition at line 617 of file GaussianProcessRegression.cpp.

619{
620 if (!hasTrainingPermutation()) return input;
622}

◆ physicalPriorMeanActive()

bool gpr::GaussianProcessRegression::physicalPriorMeanActive ( ) const
inlinenodiscardnoexcept

True when the ZBL or Morse prior mean is the one evaluation uses.

Definition at line 2003 of file GaussianProcessRegression.h.

2004 {
2005 return priorMeanActive();
2006 }

◆ planObjectiveBackend()

void gpr::GaussianProcessRegression::planObjectiveBackend ( const EigenMatrix & x,
const Eigen::VectorXd & y )
protected

Update the plan from the dense factor just formed at this order.

Definition at line 68 of file KrylovObjective.cpp.

70{
71 const Eigen::Index n = L.rows();
72 if (n == 0 || n != y.size()) return;
73 ObjectivePlan plan;
74 plan.order = n;
75 const Eigen::Index hyperparameters =
76 sexpat_cov_func->combineParameters().size() +
77 (theta_includes_likelihood_noise_ ? 1 : 0);
78 plan.dense_flops = linalg::linop::denseObjectiveFlops(n, hyperparameters);
79 plan.krylov_flops = std::numeric_limits<double>::infinity();
80 krylov_objective_.plan = plan;
81 const auto added = krylovAddedDiagonal(x);
82 const double objective_tolerance = scg_opt_settings.common.tolerance_func;
83 if (!added || !(objective_tolerance > 0.0)) return;
84 linalg::linop::KrylovObjectiveInputs in;
85 in.order = n;
86 in.hyperparameters = hyperparameters;
87 in.matvec_flops = 2.0 * static_cast<double>(n) * static_cast<double>(n);
88 in.column_flops = static_cast<double>(n);
89 in.noise_floor = added->minCoeff();
90 in.relative_tolerance =
92 objective_tolerance, in.noise_floor) /
93 y.norm();
94 // The fewest probes from which the variance target can be read; more
95 // only raise the Krylov count.
96 in.probes = 2;
97 in.residual_trace = linalg::linop::schurResidualTraces(L);
98 const auto krylov = linalg::linop::planKrylovObjective(in);
99 plan.krylov_flops = krylov.flops;
100 plan.rank = krylov.rank;
101 plan.krylov = krylov.flops < plan.dense_flops;
102 krylov_objective_.plan = plan;
103}
static double residualTolerance(double objective_tolerance, double noise_floor)
std::vector< double > schurResidualTraces(const Eigen::MatrixXd &L)
KrylovPlan planKrylovObjective(const KrylovObjectiveInputs &in)
Definition CostModel.cpp:49
double denseObjectiveFlops(Eigen::Index order, Eigen::Index hyperparameters)
Definition CostModel.cpp:15

◆ poolDescriptorScaleByTies()

void gpr::GaussianProcessRegression::poolDescriptorScaleByTies ( Eigen::VectorXd & scales) const

Pools a per-pair-type motion scale, sqrt of the summed feature variances of the type, over each tie group: every tied member takes the scale of the union of its group's pairs, the base type's own statistic, so a tied model seeds and anchors exactly as the base model does. Released types keep their own scale.

Definition at line 750 of file GaussianProcessRegression.cpp.

752{
753 const auto& ties = length_scale_ties_;
754 if (!use_length_scale_ties_ || !ties.valid || scales.size() != ties.count())
755 return;
756 std::vector<double> variance(ties.parent.size(), 0.0);
757 std::vector<int> members(ties.parent.size(), 0);
758 for (Index_t t = 0; t < ties.count(); ++t) {
759 const auto lead = static_cast<std::size_t>(ties.leader[t]);
760 ++members[lead];
761 const double scale = scales(t);
762 if (std::isfinite(scale) && scale > 0.0)
763 variance[lead] += scale * scale;
764 }
765 for (Index_t t = 0; t < ties.count(); ++t) {
766 const auto lead = static_cast<std::size_t>(ties.leader[t]);
767 // A group of one keeps its scale bit for bit.
768 if (members[lead] == 1) continue;
769 scales(t) = std::sqrt(variance[lead]);
770 }
771}

◆ populationPrior()

const priors::PopulationPrior & gpr::GaussianProcessRegression::populationPrior ( ) const
inlinenodiscardnoexcept

Definition at line 1764 of file GaussianProcessRegression.h.

1766 {
1767 return population_prior_;
1768 }

◆ predictDevicePosterior()

bool gpr::GaussianProcessRegression::predictDevicePosterior ( Observation & image,
bool variance )
protected

Definition at line 307 of file DevicePosterior.cpp.

308{
309 return false;
310}

◆ prepareAnalyticMeanHessian()

GaussianProcessRegression::MeanHessianAction gpr::GaussianProcessRegression::prepareAnalyticMeanHessian ( const Coord & R)
nodiscard

The analytic part of prepareMeanHessian. Empty when this model's mean has no analytic Hessian contraction; the returned action never falls back to a stencil of the mean gradient. Unlike prepareMeanHessian it also contracts the Cholesky weights of an HS-SVD model whose stable basis was not built.

Definition at line 2560 of file ActivePosterior.cpp.

2561{
2562 return prepareMeanHessianAction(R, true);
2563}

◆ prepareMeanHessian()

GaussianProcessRegression::MeanHessianAction gpr::GaussianProcessRegression::prepareMeanHessian ( const Coord & R)
nodiscard

Linear action of the physical posterior mean at one geometry.

The operator is consumed while this fitted model remains unchanged. An exact kernel that returns no action, or an action that returns false, has refused. In a mean with one exact term and one generic term, refusal of the exact term is final. Outside an active posterior, a prepared HS-SVD product is the action before the exact MAP kernel is consulted. A prepared block that does not apply has refused; the exact kernel and the stencil are not substitutes.

Definition at line 2554 of file ActivePosterior.cpp.

2555{
2556 return prepareMeanHessianAction(R, false);
2557}

◆ prepareMeanHessianVectorHssvd()

bool gpr::GaussianProcessRegression::prepareMeanHessianVectorHssvd ( const Coord & R,
PreparedHssvdHessianVector & prepared ) const
nodiscard

Definition at line 1636 of file Decompose.cpp.

1638{
1639 prepared = PreparedHssvdHessianVector{};
1640 if (atomic_environment_model_) return false;
1641 // These descriptor weights differentiate the MAP mean. Mixture and
1642 // feature-model means use their own derivative dispatch.
1643 const bool map_mean = uncertainty_mode_ == UncertaintyMode::MAP ||
1644 uncertainty_mode_ == UncertaintyMode::EB ||
1645 uncertainty_mode_ == UncertaintyMode::LAPLACE_SLICE;
1646 const bool feature_mean =
1647 rff_model_.isBuilt() &&
1648 (rff_replaces_exact_ ||
1649 (uncertainty_mode_ == UncertaintyMode::LAPLACE_SLICE &&
1650 rff_features_ > 0));
1651 if (!map_mean || feature_mean || active_posterior_ || !sexpat_cov_func ||
1652 sexpat_cov_func->usesManifoldChart() ||
1653 sexpat_cov_func->usesGeodesicHeatKernel())
1654 return false;
1655 hssvd_last_local_active_set_config_count_for_testing_ = 0;
1656 hssvd_last_local_active_set_observation_count_for_testing_ = 0;
1657 hssvd_last_local_active_set_condition_for_testing_ = 0.0;
1658 const bool descriptor_mean_ready =
1659 use_hssvd_backend_ ? hssvd_basis_valid_ && hssvd_dual_kernel_
1660 : descriptor_predictor_ready_;
1661 // The derivative follows the fitted mean representation. Cholesky and
1662 // spectral factorization supply weights to the same analytic descriptor
1663 // contraction, independently of how those weights are obtained.
1664 if (!descriptor_mean_ready || hssvd_dual_predict_weights_.size() == 0 ||
1665 hssvd_train_qtil_.rows() == 0 || R.rows() != 1 ||
1666 sexpat_cov_func == nullptr)
1667 return false;
1668
1669 const Eigen::Index ntrain = hssvd_train_qtil_.rows();
1670 const Eigen::Index dof = R.cols();
1671 if (full_cartesian_training_dimension_ != dof) return false;
1672 if (hssvd_dual_predict_weights_.size() != ntrain * (dof + 1)) return false;
1673
1674 HssvdDualLocalModel local_model;
1675 if (use_hssvd_backend_ && buildHssvdDualLocalModel(R, local_model)) {
1676 const bool ok = prepareMeanHessianVectorHssvdDualFromWeights(
1677 R, local_model.train_qtil, local_model.train_jtil,
1678 local_model.predict_weights, local_model.force_jacobian_weights,
1679 prepared);
1680 if (ok) {
1681 hssvd_last_local_active_set_config_count_for_testing_ =
1682 local_model.config_count;
1683 hssvd_last_local_active_set_observation_count_for_testing_ =
1684 local_model.observation_count;
1685 hssvd_last_local_active_set_condition_for_testing_ =
1686 local_model.condition_number;
1687 }
1688 return ok;
1689 }
1690
1691 hssvd_last_local_active_set_config_count_for_testing_ = ntrain;
1692 hssvd_last_local_active_set_observation_count_for_testing_ =
1693 hssvd_dual_predict_weights_.size();
1694 hssvd_last_local_active_set_condition_for_testing_ =
1695 hssvd_basis_.conditionNumber();
1696 return prepareMeanHessianVectorHssvdDualFromWeights(
1697 R, hssvd_train_qtil_, hssvd_train_jtil_, hssvd_dual_predict_weights_,
1698 hssvd_dual_force_jacobian_weights_, prepared);
1699}

◆ prepareTrainingKernelGeometry()

bool gpr::GaussianProcessRegression::prepareTrainingKernelGeometry ( const EigenMatrix & x,
const Eigen::VectorXd & x_ind,
TrainingKernelGeometry & out,
bool reused = false ) const
nodiscard

Definition at line 1184 of file CovarianceAssembly.cpp.

1187{
1189 // RAII timer: accumulate this build's wall into g_geom_build_seconds on
1190 // every return path (attribution probe for the incremental-geometry work).
1191 struct GeomTimer {
1192 std::chrono::steady_clock::time_point t0 =
1193 std::chrono::steady_clock::now();
1194 ~GeomTimer()
1195 {
1196 g_geom_build_seconds += std::chrono::duration<double>(
1197 std::chrono::steady_clock::now() - t0)
1198 .count();
1199 }
1200 } geom_timer;
1201 struct PrepReport {
1202 const TrainingKernelGeometry& g;
1203 double rss0 = PhaseTimers::residentMegabytes();
1204 ~PrepReport()
1205 {
1206 if (std::getenv("GPR_GEOM_DEBUG"))
1207 std::fprintf(
1208 stderr,
1209 "[geom] prepare n=%lld dims=%lld blocks=%zu streamed=%d "
1210 "rss_mb %.0f -> %.0f\n",
1211 static_cast<long long>(g.n),
1212 static_cast<long long>(g.x_loc_by_dim.size()),
1213 g.blocks.size(), g.streamed ? 1 : 0, rss0,
1214 PhaseTimers::residentMegabytes());
1215 }
1216 } prep_report{out};
1217
1218 out.clear();
1219 if (sexpat_cov_func == nullptr) return false;
1220 // The pair-distance geometry evaluates the ambient Sexpat operator; a
1221 // charted composite is not a function of pair distances.
1222 if (sexpat_cov_func->usesManifoldChart() ||
1223 sexpat_cov_func->usesGeodesicHeatKernel())
1224 return false;
1225 if (x.cols() < 2) {
1226 // The 1D path in applyCovarianceFunction takes a different code path
1227 // (blocked [Kff Kdf; Kdf D] layout). Skip the geometry cache there;
1228 // CuH2/PETMAD do not hit this branch.
1229 if (std::getenv("GPR_GEOM_DEBUG"))
1230 std::fprintf(stderr, "[geom] fallback at prepare line %d\n",
1231 __LINE__);
1232 return false;
1233 }
1234 const detail::ObservationChannelLayout channels(x_ind);
1235 if (!channels.valid())
1236 throw std::invalid_argument(
1237 "observation channels must be grouped in order");
1238 if (x_ind.size() != x.rows() || channels.rowsPerChannel() <= 0 ||
1239 channels.block(0).count == 0)
1240 return false;
1241
1242 extractUniqueIndices(x_ind, out.uDdim);
1243 out.num_repetitive_indices = getNumberOfRepetitiveIndices(x_ind);
1244 out.n = x.rows();
1245
1246 FieldMatrixd x_loc_0, x_loc_1, x_loc_2;
1247 FieldMatrixIdx dims1(1, 1), dims2(1, 1);
1248
1249 x_loc_0.resize(out.num_repetitive_indices, x.cols() + 1);
1250 x_loc_0.setZero();
1251 x_loc_1.resize(out.num_repetitive_indices, x.cols() + 1);
1252 x_loc_1.setZero();
1253 x_loc_2.resize(out.num_repetitive_indices, x.cols() + 1);
1254 x_loc_2.setZero();
1255
1256 extractCoordinatesByIndex(x, x_ind, 0, x_loc_0);
1257
1258 const Eigen::Index coordinate_dimensions =
1259 3 * sexpat_cov_func->getConfInfo().atoms_mov.type.size();
1260 if (coordinate_dimensions <= 0 || x.cols() < coordinate_dimensions)
1261 return false;
1262 out.shared_coordinates =
1263 channels.repeatsCoordinates(x, coordinate_dimensions);
1264
1265 // The energy block supplies the base distance at unit lengthscale.
1266 // Repeated Cartesian positions share it across every channel block;
1267 // distinct positions require each derivative block's own distance.
1268 if (!sexpat_cov_func->buildSharedDistanceForTrainingGeometry(
1269 x_loc_0, out.shared_distance_neg_per_pt)) {
1270 if (std::getenv("GPR_GEOM_DEBUG"))
1271 std::fprintf(
1272 stderr,
1273 "[geom] fallback: shared distance (n_pt=%d rows=%lld)\n",
1274 static_cast<int>(atoms_config.n_pt),
1275 static_cast<long long>(x.rows()));
1276 if (std::getenv("GPR_GEOM_DEBUG"))
1277 std::fprintf(stderr, "[geom] fallback at prepare line %d\n",
1278 __LINE__);
1279 return false;
1280 }
1281
1282 // The pair-local tiles serve every assembly and gradient that can use
1283 // them; the block geometry below remains for the others.
1284 if (use_pair_local_tiles_ && out.shared_coordinates)
1285 (void)pairlocal::buildGeometry(sexpat_cov_func->getConfInfo(),
1286 Eigen::MatrixXd(x_loc_0), out.pair_local,
1287 sexpat_cov_func->farFieldRadius());
1288
1289 // Kff: (0, 0), derivative_options = 0. Distance field left empty;
1290 // shared tensor populated above.
1291 {
1292 TrainingKernelGeometryBlock b;
1293 b.block_n = 0;
1294 b.block_m = 0;
1295 b.derivative_options = 0;
1296 if (!sexpat_cov_func->buildCrossBlockDerivativesOnly(
1297 x_loc_0, x_loc_0, /*derivative_options=*/0, dims1, dims2,
1298 b.geometry)) {
1299 if (std::getenv("GPR_GEOM_DEBUG"))
1300 std::fprintf(stderr, "[geom] fallback at prepare line %d\n",
1301 __LINE__);
1302 return false;
1303 }
1304 out.blocks.push_back(std::move(b));
1305 }
1306
1307 const uint8_t full_grad = OptionsForGradCalculation::D1 |
1310 {
1311 // Footprint of the cached derivative tensors: one per-pair-type
1312 // n_conf x n_conf field for each D1 block and three for each of
1313 // the D(D+1)/2 full blocks.
1314 // Measured, not modelled: build one full block and count its
1315 // bytes (the walked builder stores more than the three per-pair-type
1316 // fields its interface names), then scale by the block count.
1317 const double D = static_cast<double>(out.uDdim.size());
1318 double bytes = 0.0;
1319 if (out.uDdim.size() > 0) {
1320 FieldMatrixIdx d1(1, 1), d2(1, 1);
1321 d1(0, 0) = static_cast<Index_t>(out.uDdim[0]);
1322 d2(0, 0) = d1(0, 0);
1323 FieldMatrixd x_probe = x_loc_0;
1324 x_probe.setZero();
1325 extractCoordinatesByIndex(x, x_ind, d1(0, 0), x_probe);
1326 SexpatCF::CrossBlockGeometry probe;
1327 if (sexpat_cov_func->buildCrossBlockDerivativesOnly(
1328 x_probe, x_probe,
1332 d1, d2, probe)) {
1333 auto field_bytes = [](const std::vector<FieldMatrixd>& v) {
1334 double b = 0.0;
1335 for (const auto& m: v)
1336 b += static_cast<double>(m.size()) * sizeof(double);
1337 return b;
1338 };
1339 const double per_full_block =
1340 field_bytes(probe.d1) + field_bytes(probe.d2) +
1341 field_bytes(probe.d12) + field_bytes(probe.distance);
1342 const double per_d1_block = field_bytes(probe.d1);
1343 bytes = per_full_block * D * (D + 1.0) / 2.0 + per_d1_block * D;
1344 }
1345 }
1346 // The derivative cache competes with dense fit workspaces. Large
1347 // workloads use factored derivatives; smaller caches may spill as
1348 // allocation headroom decreases.
1349 const double n_joint = static_cast<double>(x.rows());
1350 const double working_set = 4.0 * n_joint * n_joint * sizeof(double);
1351 // With the pair-local tiles no consumer reads the cached block
1352 // tensors on the fit path; the streamed factors serve the rest.
1353 // Workload size chooses the derivative arithmetic. Memory pressure
1354 // changes only storage: a cache that spills uses the same walked
1355 // derivatives, so ranks with different headroom produce the same bits.
1356 const bool force_streamed =
1357 std::getenv("GPR_GEOM_FORCE_STREAM") != nullptr;
1358 // Explicit streaming of one-use geometry requests the factored
1359 // builder. A reusable cache keeps its arithmetic when it spills.
1360 const bool factored_derivatives =
1361 out.shared_coordinates &&
1362 (out.pair_local.valid ||
1363 (!reused && (bytes > working_set || force_streamed)));
1364 const auto budget =
1365 factored_derivatives
1367 : geometryCacheBudgetBytes(backend().memorySharingRanks());
1368 out.streamed = !out.shared_coordinates || factored_derivatives ||
1369 (budget && bytes > static_cast<double>(*budget)) ||
1370 force_streamed;
1371 if (out.streamed) {
1372 const Index_t max_dim =
1373 out.uDdim.size() > 0
1374 ? static_cast<Index_t>(out.uDdim.maxCoeff())
1375 : 0;
1376 out.x_loc_by_dim.assign(static_cast<std::size_t>(max_dim) + 1,
1377 FieldMatrixd());
1378 out.x_loc_by_dim[0] = x_loc_0;
1379 if (pairLocalCoversGeometry(out)) {
1380 out.lazy_factors =
1381 std::make_shared<LazyFactoredTrainingGeometry>(
1382 sexpat_cov_func->getConfInfo(), x_loc_0,
1383 sexpat_cov_func->farFieldRadius());
1384 } else if (factored_derivatives) {
1386 sexpat_cov_func->getConfInfo(), x_loc_0, out.factors,
1387 sexpat_cov_func->farFieldRadius());
1388 }
1389 if (std::getenv("GPR_GEOM_DEBUG"))
1390 std::fprintf(
1391 stderr,
1392 "[geom] streamed geometry: cache would be %.2f GB "
1393 "against a %.2f GB budget\n",
1394 bytes / 1e9,
1395 budget ? static_cast<double>(*budget) / 1e9 : -1.0);
1396 }
1397 }
1398 auto build_derivative_geometry =
1399 [&](const FieldMatrixd& x1_block, const FieldMatrixd& x2_block,
1400 const uint8_t derivative_options, const FieldMatrixIdx& block_dims1,
1401 const FieldMatrixIdx& block_dims2,
1402 SexpatCF::CrossBlockGeometry& geometry) -> bool {
1403 if (out.streamed) {
1404 // Descriptor only; the consumer rebuilds the tensors per block.
1405 geometry = SexpatCF::CrossBlockGeometry{};
1406 geometry.derivative_options = derivative_options;
1407 geometry.valid = true;
1408 return true;
1409 }
1410 if (derivative_options != 0) {
1411 ++out.derivative_geometry_build_calls_for_testing;
1412 }
1413 return sexpat_cov_func->buildCrossBlockDerivativesOnly(
1414 x1_block, x2_block, derivative_options, block_dims1, block_dims2,
1415 geometry);
1416 };
1417
1418 for (Index_t n = 0; n < out.uDdim.size(); ++n) {
1419 dims1(0, 0) = static_cast<Index_t>(out.uDdim[n]);
1420 x_loc_1.setZero();
1421 extractCoordinatesByIndex(x, x_ind, dims1(0, 0), x_loc_1);
1422 if (out.streamed &&
1423 dims1(0, 0) < static_cast<Index_t>(out.x_loc_by_dim.size())) {
1424 out.x_loc_by_dim[static_cast<std::size_t>(dims1(0, 0))] = x_loc_1;
1425 }
1426
1427 // Kdf at (block_n, 0): D1 only. ginput4 equivalent.
1428 {
1429 TrainingKernelGeometryBlock b;
1430 b.block_n = dims1(0, 0);
1431 b.block_m = 0;
1432 b.derivative_options = OptionsForGradCalculation::D1;
1433 if (!build_derivative_geometry(x_loc_1, x_loc_0,
1435 dims2, b.geometry)) {
1436 if (std::getenv("GPR_GEOM_DEBUG"))
1437 std::fprintf(stderr, "[geom] fallback at prepare line %d\n",
1438 __LINE__);
1439 return false;
1440 }
1441 out.blocks.push_back(std::move(b));
1442 }
1443
1444 // D at (block_n, block_n): full grad on (x_loc_1, x_loc_1). ginput2.
1445 {
1446 TrainingKernelGeometryBlock b;
1447 b.block_n = dims1(0, 0);
1448 b.block_m = dims1(0, 0);
1449 b.derivative_options = full_grad;
1450 if (!build_derivative_geometry(x_loc_1, x_loc_1, full_grad, dims1,
1451 dims1, b.geometry)) {
1452 if (std::getenv("GPR_GEOM_DEBUG"))
1453 std::fprintf(stderr, "[geom] fallback at prepare line %d\n",
1454 __LINE__);
1455 return false;
1456 }
1457 out.blocks.push_back(std::move(b));
1458 }
1459
1460 // Kdf2 at (block_n, block_m) with block_m > block_n: ginput3.
1461 for (Index_t m = n + 1; m < out.uDdim.size(); ++m) {
1462 dims2(0, 0) = static_cast<Index_t>(out.uDdim[m]);
1463 x_loc_2.setZero();
1464 extractCoordinatesByIndex(x, x_ind, dims2(0, 0), x_loc_2);
1465 TrainingKernelGeometryBlock b;
1466 b.block_n = dims1(0, 0);
1467 b.block_m = dims2(0, 0);
1468 b.derivative_options = full_grad;
1469 if (!build_derivative_geometry(x_loc_1, x_loc_2, full_grad, dims1,
1470 dims2, b.geometry)) {
1471 if (std::getenv("GPR_GEOM_DEBUG"))
1472 std::fprintf(stderr, "[geom] fallback at prepare line %d\n",
1473 __LINE__);
1474 return false;
1475 }
1476 out.blocks.push_back(std::move(b));
1477 }
1478 }
1479
1480 // Index blocks by (block_n, block_m) so the gradient walk can find
1481 // cached geometry per block without linear scan.
1482 out.block_index_by_nm.clear();
1483 for (std::size_t i = 0; i < out.blocks.size(); ++i) {
1484 const auto& blk = out.blocks[i];
1485 out.block_index_by_nm[{blk.block_n, blk.block_m}] = i;
1486 }
1487 out.n_pairtypes =
1488 static_cast<Index_t>(out.shared_distance_neg_per_pt.size());
1489
1490 // Per-rank owned-subset geometry. At np>1 each rank's owned observation
1491 // subset is distinct (determined by the BLACS grid below), so the full
1492 // geometry's blocks don't directly apply to the permuted gradient walk.
1493 // At np=1 the subset has the full shape, but it keeps the same assembly
1494 // path as distributed runs and preserves the validated dimer trajectory.
1495#ifdef GPR_LINALG_SCALAPACK
1496 if (out.streamed) {
1497 // The per-rank subsets copy the cached tensors; a streamed geometry
1498 // has none and its consumers take the full-block path.
1499 out.has_per_rank_subset = false;
1500 out.valid = true;
1501 return true;
1502 }
1503 auto& _mpi_st_subset = backend().distributed();
1504 _mpi_st_subset.initialize();
1505 const Index_t proc_rows = static_cast<Index_t>(_mpi_st_subset.nprow());
1506 const Index_t proc_cols = static_cast<Index_t>(_mpi_st_subset.npcol());
1507 const Index_t my_row = static_cast<Index_t>(_mpi_st_subset.myrow());
1508 const Index_t my_col = static_cast<Index_t>(_mpi_st_subset.mycol());
1509 std::vector<Index_t> owned_obs_rows;
1510 std::vector<Index_t> owned_obs_cols;
1511 for (Index_t obs = 0; obs < out.num_repetitive_indices; ++obs) {
1512 if (obs % proc_rows == my_row) owned_obs_rows.push_back(obs);
1513 if (obs % proc_cols == my_col) owned_obs_cols.push_back(obs);
1514 }
1515 const auto build_obs_subset = [&](Index_t dim_ind,
1516 const std::vector<Index_t>& obs_inds,
1517 FieldMatrixd& x_loc_subset) {
1518 x_loc_subset.resize(static_cast<Index_t>(obs_inds.size()),
1519 x.cols() + 1);
1520 x_loc_subset.setZero();
1521 const Eigen::Index start =
1522 observationChannelBlock(x_ind, dim_ind).start;
1523 for (std::size_t local_idx = 0; local_idx < obs_inds.size();
1524 ++local_idx) {
1525 x_loc_subset.block(static_cast<Index_t>(local_idx), 0, 1,
1526 x.cols()) =
1527 x.block(start + obs_inds[local_idx], 0, 1, x.cols());
1528 }
1529 };
1530 const auto fill_subset = [&](TrainingKernelGeometrySubset& subset,
1531 const std::vector<Index_t>& obs_rows,
1532 const std::vector<Index_t>& obs_cols) -> bool {
1533 subset.clear();
1534 if (obs_rows.empty() || obs_cols.empty()) {
1535 subset.valid = true;
1536 return true;
1537 }
1538 // When this rank owns the entire observation set on both axes (np=1,
1539 // and any full-owning rank) the subset is built on exactly the full
1540 // geometry's coordinates, so the shared distance and every block are
1541 // bit-for-bit identical to the full geometry's. Reuse them (the
1542 // (m,n) shape via transpose) instead of recomputing dist_at +
1543 // per-pair derivatives. The geometry is a deterministic function of
1544 // the coordinates, so this is bit-identical; np>1 partial subsets
1545 // skip the reuse and rebuild as before.
1546 const auto is_full_obs = [&](const std::vector<Index_t>& inds) {
1547 if (static_cast<Index_t>(inds.size()) !=
1548 out.num_repetitive_indices) {
1549 if (std::getenv("GPR_GEOM_DEBUG"))
1550 std::fprintf(
1551 stderr,
1552 "[geom] subset contains %zu of %lld observations\n",
1553 inds.size(),
1554 static_cast<long long>(out.num_repetitive_indices));
1555 return false;
1556 }
1557 for (std::size_t i = 0; i < inds.size(); ++i)
1558 if (inds[i] != static_cast<Index_t>(i)) return false;
1559 return true;
1560 };
1561 const bool diag_reusable_from_full =
1562 is_full_obs(obs_rows) && is_full_obs(obs_cols);
1563 FieldMatrixd x_loc_0_rows, x_loc_0_cols;
1564 build_obs_subset(0, obs_rows, x_loc_0_rows);
1565 build_obs_subset(0, obs_cols, x_loc_0_cols);
1566
1567 // Shared distance for this rank's (rows × cols) shape.
1568 if (diag_reusable_from_full) {
1569 subset.shared_distance_neg_per_pt = out.shared_distance_neg_per_pt;
1570 } else {
1571 FieldMatrixd unit_length_scale(1,
1572 sexpat_cov_func->getConfInfo().n_pt);
1573 unit_length_scale.setOnes();
1574 aux::Distance distance_calc;
1575 distance_calc.setFarFieldRadius(sexpat_cov_func->farFieldRadius());
1576 std::vector<FieldMatrixd> dist_pt;
1577 distance_calc.dist_at_vec(x_loc_0_rows, x_loc_0_cols,
1578 sexpat_cov_func->getConfInfo(),
1579 unit_length_scale, dist_pt);
1580 if (dist_pt.size() !=
1581 static_cast<std::size_t>(sexpat_cov_func->getConfInfo().n_pt)) {
1582 if (std::getenv("GPR_GEOM_DEBUG"))
1583 std::fprintf(stderr, "[geom] fallback at prepare line %d\n",
1584 __LINE__);
1585 return false;
1586 }
1587 subset.shared_distance_neg_per_pt.resize(dist_pt.size());
1588 for (std::size_t pt = 0; pt < dist_pt.size(); ++pt) {
1589 subset.shared_distance_neg_per_pt[pt] = -dist_pt[pt];
1590 }
1591 }
1592 subset.n_rows = static_cast<Index_t>(obs_rows.size());
1593 subset.n_cols = static_cast<Index_t>(obs_cols.size());
1594
1595 FieldMatrixIdx ds1(1, 1), ds2(1, 1);
1596 // Kff at (0, 0) -- block value uses shared kernel directly; we
1597 // store an empty-derivatives placeholder block so find((0, 0))
1598 // returns a valid entry.
1599 {
1600 TrainingKernelGeometryBlock b;
1601 b.block_n = 0;
1602 b.block_m = 0;
1603 b.derivative_options = 0;
1604 if (!sexpat_cov_func->buildCrossBlockDerivativesOnly(
1605 x_loc_0_rows, x_loc_0_cols, /*derivative_options=*/0, ds1,
1606 ds2, b.geometry)) {
1607 if (std::getenv("GPR_GEOM_DEBUG"))
1608 std::fprintf(stderr, "[geom] fallback at prepare line %d\n",
1609 __LINE__);
1610 return false;
1611 }
1612 subset.blocks.push_back(std::move(b));
1613 }
1614 FieldMatrixd x_loc_1_rows, x_loc_1_cols, x_loc_2_rows, x_loc_2_cols;
1615 for (Index_t n = 0; n < out.uDdim.size(); ++n) {
1616 ds1(0, 0) = static_cast<Index_t>(out.uDdim[n]);
1617 build_obs_subset(ds1(0, 0), obs_rows, x_loc_1_rows);
1618 build_obs_subset(ds1(0, 0), obs_cols, x_loc_1_cols);
1619
1620 // Kdf at (block_n, 0): reuse the full geometry's identical block
1621 // when this rank owns the whole obs set on both axes.
1622 {
1623 TrainingKernelGeometryBlock b;
1624 b.block_n = ds1(0, 0);
1625 b.block_m = 0;
1626 b.derivative_options = OptionsForGradCalculation::D1;
1627 bool reused = false;
1628 if (diag_reusable_from_full) {
1629 const auto it = out.block_index_by_nm.find({ds1(0, 0), 0});
1630 if (it != out.block_index_by_nm.end() &&
1631 out.blocks[it->second].derivative_options ==
1632 b.derivative_options) {
1633 b.geometry = out.blocks[it->second].geometry;
1634 reused = true;
1635 }
1636 }
1637 if (!reused &&
1638 !build_derivative_geometry(x_loc_1_rows, x_loc_0_cols,
1640 ds1, ds2, b.geometry)) {
1641 if (std::getenv("GPR_GEOM_DEBUG"))
1642 std::fprintf(stderr,
1643 "[geom] fallback at prepare line %d\n",
1644 __LINE__);
1645 return false;
1646 }
1647 subset.blocks.push_back(std::move(b));
1648 }
1649 // D at (block_n, block_n): reuse the full geometry's identical
1650 // diagonal block when this rank owns the whole obs set on both
1651 // axes (bit-identical copy, skips a rebuild); otherwise build.
1652 {
1653 TrainingKernelGeometryBlock b;
1654 b.block_n = ds1(0, 0);
1655 b.block_m = ds1(0, 0);
1656 b.derivative_options = OptionsForGradCalculation::D1 |
1659 bool reused = false;
1660 if (diag_reusable_from_full) {
1661 const auto it =
1662 out.block_index_by_nm.find({ds1(0, 0), ds1(0, 0)});
1663 if (it != out.block_index_by_nm.end() &&
1664 out.blocks[it->second].derivative_options ==
1665 b.derivative_options) {
1666 b.geometry = out.blocks[it->second].geometry;
1667 reused = true;
1668 }
1669 }
1670 if (!reused &&
1671 !build_derivative_geometry(x_loc_1_rows, x_loc_1_cols,
1672 b.derivative_options, ds1, ds1,
1673 b.geometry)) {
1674 if (std::getenv("GPR_GEOM_DEBUG"))
1675 std::fprintf(stderr,
1676 "[geom] fallback at prepare line %d\n",
1677 __LINE__);
1678 return false;
1679 }
1680 subset.blocks.push_back(std::move(b));
1681 }
1682 // Kdf2 at (n, m) and (m, n) for m > n. The permuted gradient
1683 // walk hits both shapes: (df_rows, dg_cols) for (n, m) and
1684 // (dg_rows, df_cols) for (m, n). Build both so dispatch covers
1685 // every block.
1686 for (Index_t m = n + 1; m < out.uDdim.size(); ++m) {
1687 ds2(0, 0) = static_cast<Index_t>(out.uDdim[m]);
1688 build_obs_subset(ds2(0, 0), obs_rows, x_loc_2_rows);
1689 build_obs_subset(ds2(0, 0), obs_cols, x_loc_2_cols);
1690 {
1691 TrainingKernelGeometryBlock b;
1692 b.block_n = ds1(0, 0);
1693 b.block_m = ds2(0, 0);
1694 b.derivative_options = OptionsForGradCalculation::D1 |
1697 bool reused = false;
1698 if (diag_reusable_from_full) {
1699 const auto it =
1700 out.block_index_by_nm.find({ds1(0, 0), ds2(0, 0)});
1701 if (it != out.block_index_by_nm.end() &&
1702 out.blocks[it->second].derivative_options ==
1703 b.derivative_options) {
1704 b.geometry = out.blocks[it->second].geometry;
1705 reused = true;
1706 }
1707 }
1708 if (!reused &&
1709 !build_derivative_geometry(x_loc_1_rows, x_loc_2_cols,
1710 b.derivative_options, ds1,
1711 ds2, b.geometry)) {
1712 if (std::getenv("GPR_GEOM_DEBUG"))
1713 std::fprintf(stderr,
1714 "[geom] fallback at prepare line %d\n",
1715 __LINE__);
1716 return false;
1717 }
1718 subset.blocks.push_back(std::move(b));
1719 }
1720 {
1721 TrainingKernelGeometryBlock b;
1722 b.block_n = ds2(0, 0);
1723 b.block_m = ds1(0, 0);
1724 b.derivative_options = OptionsForGradCalculation::D1 |
1727 // (m,n) is the transpose of the full geometry's (n,m)
1728 // block: dist(m,n)=dist(n,m)^T, and the first/second
1729 // derivative roles swap with the row/col axes, so
1730 // d1(m,n)=d2(n,m)^T, d2(m,n)=d1(n,m)^T, d12(m,n)=
1731 // d12(n,m)^T. The kernel is symmetric so this equals a
1732 // rebuild bit-for-bit. Only fires when this rank owns
1733 // the full obs set on both axes.
1734 bool reused = false;
1735 if (diag_reusable_from_full) {
1736 const auto it =
1737 out.block_index_by_nm.find({ds1(0, 0), ds2(0, 0)});
1738 if (it != out.block_index_by_nm.end() &&
1739 out.blocks[it->second].derivative_options ==
1740 b.derivative_options) {
1741 const auto& src = out.blocks[it->second].geometry;
1742 auto transpose_vec =
1743 [](const std::vector<FieldMatrixd>& in,
1744 std::vector<FieldMatrixd>& dst) {
1745 dst.resize(in.size());
1746 for (std::size_t p = 0; p < in.size(); ++p)
1747 dst[p] = in[p].transpose();
1748 };
1749 b.geometry.derivative_options =
1750 src.derivative_options;
1751 transpose_vec(src.distance, b.geometry.distance);
1752 transpose_vec(src.d2, b.geometry.d1);
1753 transpose_vec(src.d1, b.geometry.d2);
1754 transpose_vec(src.d12, b.geometry.d12);
1755 b.geometry.valid = src.valid;
1756 reused = true;
1757 }
1758 }
1759 if (!reused &&
1760 !build_derivative_geometry(x_loc_2_rows, x_loc_1_cols,
1761 b.derivative_options, ds2,
1762 ds1, b.geometry)) {
1763 if (std::getenv("GPR_GEOM_DEBUG"))
1764 std::fprintf(stderr,
1765 "[geom] fallback at prepare line %d\n",
1766 __LINE__);
1767 return false;
1768 }
1769 subset.blocks.push_back(std::move(b));
1770 }
1771 }
1772 }
1773 subset.block_index_by_nm.clear();
1774 for (std::size_t i = 0; i < subset.blocks.size(); ++i) {
1775 const auto& blk = subset.blocks[i];
1776 subset.block_index_by_nm[{blk.block_n, blk.block_m}] = i;
1777 }
1778 subset.valid = true;
1779 return true;
1780 };
1781 if (!fill_subset(out.rows_cols, owned_obs_rows, owned_obs_cols) ||
1782 !fill_subset(out.cols_rows, owned_obs_cols, owned_obs_rows)) {
1783 if (std::getenv("GPR_GEOM_DEBUG"))
1784 std::fprintf(stderr, "[geom] fallback at prepare line %d\n",
1785 __LINE__);
1786 return false;
1787 }
1788 out.has_per_rank_subset = true;
1789#endif
1790
1791 out.valid = true;
1792 return true;
1793}
void dist_at_vec(const gpr::Coord &x1, const gpr::Coord &x2, const gpr::AtomsConfiguration &conf_info, const gpr::FieldMatrixd &lengthscale, std::vector< gpr::FieldMatrixd > &dist)
Similar to dist_at but calculates vector of distances for every pair of moving and frozen atoms.
Definition Distance.cpp:796
void setFarFieldRadius(double radius)
Definition Distance.cpp:299
eon_relax_band_t eon_relax_surface_fn void eon_relax_outcome_t * out
std::optional< std::int64_t > AvailableMemory
bool buildGeometry(const AtomsConfiguration &configuration, const Eigen::MatrixXd &positions, Geometry &geometry)
bool buildFactoredTrainingGeometry(const AtomsConfiguration &conf_info, const FieldMatrixd &x_loc, FactoredTrainingGeometry &out, double far_field_radius=0.0)
double g_geom_build_seconds
static int geometry_builds

◆ prepareTrainingPermutation()

void gpr::GaussianProcessRegression::prepareTrainingPermutation ( const Eigen::VectorXd & x_ind)
protected

Definition at line 430 of file GaussianProcessRegression.cpp.

432{
433#ifdef GPR_LINALG_SCALAPACK
434 // Match the observation-tile size so the trainstep gradient can take the
435 // observation-tiled fast path (one row per stored channel). Grid
436 // shape stays the DistributedState default (near-square): a forced 1D
437 // nprow=nprocs grid was measured to anti-scale the pure-CPU HostTask
438 // trainstep at np>=8 relative to the square grid.
439 const int tile_size =
440 static_cast<int>(detail::storedObservationChannelCount(x_ind));
441 if (tile_size > 0) backend().distributed().initialize(tile_size);
443#else
445#endif
446}

◆ prepareTrainingPermutationLocal()

void gpr::GaussianProcessRegression::prepareTrainingPermutationLocal ( const Eigen::VectorXd & x_ind)
protected

Definition at line 448 of file GaussianProcessRegression.cpp.

450{
451 if (x_ind.size() == 0) {
454 return;
455 }
458 static_cast<Eigen::Index>(training_permutation_.perm.size()) ==
459 x_ind.size();
460}
StructuredPermutation buildObservationTiledPermutation(const Eigen::VectorXd &ind_Ddim)

◆ priorMeanStatistic()

PriorMeanStatistic gpr::GaussianProcessRegression::priorMeanStatistic ( ) const
inlinenodiscardnoexcept

Definition at line 1706 of file GaussianProcessRegression.h.

1707 {
1708 return prior_mean_statistic_;
1709 }

◆ profileSplitTotals()

const ProfileSplitTotals & gpr::GaussianProcessRegression::profileSplitTotals ( ) const
inlinenodiscardnoexcept

Definition at line 1540 of file GaussianProcessRegression.h.

1541 {
1542 return profile_split_totals_;
1543 }

◆ recordHyperparameterDataTerm()

virtual void gpr::GaussianProcessRegression::recordHyperparameterDataTerm ( double ,
double  )
inlineprotectedvirtual

Rows and y^T C^{-1} y of the posterior weights just written. The Student-t gradient scale reads them, so a later update, append, retain or refit cannot keep an earlier training vector's weight.

Reimplemented in gpr::StudentTProcessRegression.

Definition at line 3573 of file GaussianProcessRegression.h.

3575 {
3576 }

◆ reduceTiedLengthScaleGradient()

void gpr::GaussianProcessRegression::reduceTiedLengthScaleGradient ( Eigen::VectorXd & gradient) const

J^T g: each leader's gradient entry becomes the sum over its group, the derivative of the objective restricted to the tied subspace, and the held members' entries become zero.

Definition at line 773 of file GaussianProcessRegression.cpp.

775{
776 // J^T g: each leader's entry becomes the sum over its group, the
777 // derivative of the objective restricted to the tied subspace; the
778 // members, held by the fit, carry none.
779 const auto& ties = length_scale_ties_;
780 if (!use_length_scale_ties_ || !ties.valid ||
781 gradient.size() < 1 + ties.count())
782 return;
783 std::vector<double> sum(ties.parent.size(), 0.0);
784 for (Index_t t = 0; t < ties.count(); ++t)
785 sum[static_cast<std::size_t>(ties.leader[t])] += gradient(1 + t);
786 for (Index_t t = 0; t < ties.count(); ++t)
787 gradient(1 + t) =
788 ties.leader[t] == t ? sum[static_cast<std::size_t>(t)] : 0.0;
789}

◆ refreshActivePosterior()

bool gpr::GaussianProcessRegression::refreshActivePosterior ( const Observation & full_observation)
nodiscard

Condition the fixed active kernel on an extended observation suffix. Returns false when a full fit must replace the retained background.

Definition at line 2360 of file ActivePosterior.cpp.

2362{
2363 if (atomic_environment_model_) return false;
2364 if (!active_posterior_) return false;
2365 const auto retained = active_posterior_;
2366 return reconditionActivePosterior(full_observation, *retained);
2367}

◆ refreshDeviceVarianceCalibration()

void gpr::GaussianProcessRegression::refreshDeviceVarianceCalibration ( )
protected

Definition at line 311 of file DevicePosterior.cpp.

311{ }

◆ refreshFullDataPosteriorIfObjectiveStationary()

bool gpr::GaussianProcessRegression::refreshFullDataPosteriorIfObjectiveStationary ( const Observation & full_observation,
double * shift_norm_out = nullptr )
nodiscard

Refresh the full-data posterior at fixed theta when the cached objective-stationarity predictor says the MAP shift is smaller than the configured threshold. Returns false when the threshold is disabled, no Hessian cache is available, or the predicted shift is too large.

Definition at line 3830 of file Optimize.cpp.

3832{
3833 if (shift_norm_out != nullptr)
3834 *shift_norm_out = std::numeric_limits<double>::infinity();
3835 if (atomic_environment_model_) return false;
3836 // A retained active correction does not block the test: the full
3837 // fit the test stands in for rebuilds every row at the held or
3838 // stepped parameters and replaces the correction either way. Only a
3839 // pending correction or residual-model fit is a different objective.
3841 return false;
3842 last_stationarity_model_ = -1;
3844 return false;
3845 }
3846 if (std::find(scg_opt_settings.active_parameters.begin(),
3847 scg_opt_settings.active_parameters.end(),
3848 false) != scg_opt_settings.active_parameters.end()) {
3849 // The full inverse Hessian does not solve the restricted quadratic:
3850 // its cross terms can move frozen length scales. The selected
3851 // optimizer owns stationarity and warm steps in the active subspace.
3852 last_refit_kind_ = 2;
3853 last_stationarity_shift_ = std::numeric_limits<double>::infinity();
3854 return false;
3855 }
3856
3857 // The stationarity question is asked of the objective the optimizer
3858 // minimizes: the FPS subset when the training set exceeds the fit
3859 // history, else the full set. Probing the full-data objective costs
3860 // an O(N^3) evaluation per probe (45 s each on a 22-atom band at 75
3861 // configurations) while the fit itself runs on the subset.
3862 const Observation& fit_observation_ref =
3864 ? full_observation
3865 : selectOptimizationSubset(full_observation);
3866 const Observation fit_observation = fit_observation_ref;
3867 // The fitted theta is already the minimizer of this subset's objective:
3868 // no probe is needed, and the rows condition at the held theta.
3869 if (subsetFitUnchanged(fit_observation)) {
3870 ++unchanged_subset_fit_skips_;
3871 last_refit_kind_ = 0;
3872 last_stationarity_shift_ = 0.0;
3873 if (report_level >= 1) {
3874 log_man << "The fit subset is unchanged since the last converged "
3875 "fit; refreshing the posterior at fixed theta.\n";
3876 }
3877 updateModelWithFullData(full_observation);
3879 }
3880 aux::AuxiliaryFunctionality aux_func;
3881 EigenMatrix opt_R_matrix;
3882 Eigen::VectorXd opt_R_indices;
3883 Eigen::VectorXd opt_y;
3884 aux_func.assembleMatrixOfRepetitiveCoordinates(fit_observation.R,
3885 opt_R_matrix, opt_R_indices);
3886 aux_func.assembleVectorFromEnergyAndGradient(fit_observation, opt_y);
3887 subtractPriorMeanFromTargets(fit_observation.R, fit_observation.E.size(),
3888 opt_y);
3889
3890 const Eigen::VectorXd raw_theta = sexpat_cov_func->combineParameters();
3891 Eigen::VectorXd theta_reference = raw_theta;
3892 OptimizationObjectiveFrame objective_frame =
3893 enterOptimizationObjectiveFrame(opt_y, fit_observation.E.size(),
3894 &theta_reference);
3895 const double skip_threshold =
3896 objectiveStationaritySkipThreshold(theta_reference);
3897 if (!(skip_threshold > 0.0) || !std::isfinite(skip_threshold)) {
3898 leaveOptimizationObjectiveFrame(objective_frame, &theta_reference);
3899 setParameters(raw_theta);
3900 return false;
3901 }
3902 Eigen::VectorXd shift;
3903 double energy_reference = std::numeric_limits<double>::quiet_NaN();
3904 Eigen::VectorXd gradient_reference;
3905 double shift_norm = computeObjectiveStationarityShiftNorm(
3906 opt_R_matrix, opt_R_indices, opt_y, theta_reference, &shift,
3907 &energy_reference, &gradient_reference);
3908 // Under nlml_hessian_vector the scale along the gradient is the exact
3909 // Barzilai-Borwein step |g|^2 / g^T H g, with H g the NLML product at a
3910 // factor rebuilt at the reference point. Without the product, or when it
3911 // fails, the secant below supplies the scale as under finite_difference.
3912 if (!std::isfinite(shift_norm) && nlmlHessianVectorCurvatureRequested() &&
3915 "the stationarity check",
3916 "the objective has no exact NLML Hessian-vector product");
3917 } else if (!std::isfinite(shift_norm) &&
3919 double energy_here = std::numeric_limits<double>::quiet_NaN();
3920 Eigen::VectorXd gradient_here =
3921 Eigen::VectorXd::Zero(theta_reference.size());
3922 EnergyAndGradient eg_here(energy_here, gradient_here);
3923 evaluateEnergyAndGradient(theta_reference, opt_R_matrix, opt_R_indices,
3924 opt_y, eg_here);
3925 Eigen::VectorXd hessian_vector;
3926 if (std::isfinite(energy_here) && gradient_here.allFinite() &&
3927 gradient_here.norm() > 0.0 &&
3928 evaluateNlmlHessianVector(opt_R_indices, opt_R_matrix, opt_y,
3929 gradient_here, hessian_vector) &&
3930 hessian_vector.size() == gradient_here.size() &&
3931 hessian_vector.allFinite()) {
3932 energy_reference = energy_here;
3933 gradient_reference = gradient_here;
3934 const double denom = gradient_here.dot(hessian_vector);
3935 if (denom > 0.0 && std::isfinite(denom)) {
3936 const double alpha = gradient_here.squaredNorm() / denom;
3937 if (alpha > 0.0 && std::isfinite(alpha)) {
3938 shift = alpha * gradient_here;
3939 shift_norm = shift.norm();
3940 last_stationarity_model_ = 6;
3941 }
3942 }
3943 }
3944 if (!std::isfinite(shift_norm)) {
3946 "the stationarity check",
3947 "the exact NLML Hessian-vector product failed or had no "
3948 "positive curvature along the gradient");
3949 }
3950 }
3951 // No cached curvature model of the objective being fitted. Under the
3952 // leave-one-out objectives the refit runs: a one-probe secant along the
3953 // gradient measures curvature along that direction only and, from a
3954 // collapsed seed where the LOO gradient is flat, reported a
3955 // microscopic shift and held the seed for a whole run (Baker 01_hcn
3956 // under LOO, oracle count tripled). Under the marginal likelihood the
3957 // secant is the Barzilai-Borwein scale of the objective whose optimum
3958 // the previous fit certified, and it is what kept every refit at a
3959 // fraction of a second on the boards: without it every refit ran the
3960 // exact-Hessian probes (24-34 s each on 17_claisen and 16_h2po4_anion,
3961 // with the dense kernel rebuild that took both cells to the OOM killer).
3962 if (!std::isfinite(shift_norm) &&
3963 hyperparameter_objective_mode_ == HyperparameterObjectiveMode::NLML) {
3964 // The probes evaluate the same NLML the fit minimizes; through the
3965 // training geometry they apply theta to the cached per-block
3966 // geometry instead of rebuilding every pair derivative live (a
3967 // 22-atom band spent a seventh of its wall in these two probes).
3968 TrainingKernelGeometry probe_geometry;
3969 const bool probe_geometry_ready =
3971 use_training_geometry_handle_ &&
3972 prepareTrainingKernelGeometry(opt_R_matrix, opt_R_indices,
3973 probe_geometry, /*reused=*/true);
3974 const auto probe = [&](const Eigen::VectorXd& theta,
3975 EnergyAndGradient& eg) {
3976 if (probe_geometry_ready)
3977 evaluateEnergyAndGradientFromGeometry(theta, probe_geometry,
3978 opt_R_matrix,
3979 opt_R_indices, opt_y, eg);
3980 else
3981 evaluateEnergyAndGradient(theta, opt_R_matrix, opt_R_indices,
3982 opt_y, eg);
3983 };
3984 if (gradient_reference.size() == 0) {
3985 double energy_here = std::numeric_limits<double>::quiet_NaN();
3986 gradient_reference = Eigen::VectorXd::Zero(theta_reference.size());
3987 EnergyAndGradient eg_here(energy_here, gradient_reference);
3988 probe(theta_reference, eg_here);
3989 energy_reference = energy_here;
3990 }
3991 const double g_norm = gradient_reference.allFinite()
3992 ? gradient_reference.norm()
3993 : std::numeric_limits<double>::quiet_NaN();
3994 if (std::isfinite(g_norm) && g_norm > 0.0 &&
3995 std::isfinite(energy_reference)) {
3996 const double tau =
3997 std::sqrt(std::numeric_limits<double>::epsilon()) *
3998 (1.0 + theta_reference.norm());
3999 const Eigen::VectorXd s_probe =
4000 -(tau / g_norm) * gradient_reference;
4001 const Eigen::VectorXd theta_probe = theta_reference + s_probe;
4002 double energy_probe = std::numeric_limits<double>::quiet_NaN();
4003 Eigen::VectorXd gradient_probe =
4004 Eigen::VectorXd::Zero(theta_reference.size());
4005 EnergyAndGradient eg_probe(energy_probe, gradient_probe);
4006 probe(theta_probe, eg_probe);
4007 if (gradient_probe.allFinite()) {
4008 const Eigen::VectorXd y_probe =
4009 gradient_probe - gradient_reference;
4010 const double denom = s_probe.dot(y_probe);
4011 if (denom > 0.0 && std::isfinite(denom)) {
4012 const double alpha = s_probe.squaredNorm() / denom;
4013 if (alpha > 0.0 && std::isfinite(alpha)) {
4014 shift = alpha * gradient_reference;
4015 shift_norm = shift.norm();
4016 last_stationarity_model_ = 5;
4017 }
4018 }
4019 }
4020 }
4021 }
4022 // Still no curvature model (leave-one-out objectives, or a secant that
4023 // did not validate): the refit runs.
4024 if (!std::isfinite(shift_norm)) {
4025 if (shift_norm_out != nullptr) *shift_norm_out = shift_norm;
4026 last_stationarity_shift_ = shift_norm;
4027 last_stationarity_threshold_ = skip_threshold;
4028 leaveOptimizationObjectiveFrame(objective_frame, &theta_reference);
4029 setParameters(raw_theta);
4030 if (report_level >= 1) {
4031 log_man << "Objective refit: no cached curvature model for the "
4032 "fitted objective.\n";
4033 }
4034 last_refit_kind_ = 2;
4035 return false;
4036 }
4037 if (shift_norm_out != nullptr) *shift_norm_out = shift_norm;
4038 last_stationarity_shift_ = shift_norm;
4039 last_stationarity_threshold_ = skip_threshold;
4040 // A Newton step within sqrt(eps) of the skip threshold is the
4041 // curvature probe's own rounding. Hold theta instead of launching
4042 // a refit that would move the length scales by a last bit.
4043 if (!std::isfinite(shift_norm) ||
4044 gpr::numerics::exceedsThreshold(shift_norm, skip_threshold)) {
4045 // The optimum moved. The predicted shift is the Newton step of
4046 // the cached objective model at the new data: take it on descent
4047 // as the optimizer's warm start. One accepted step is not a fit:
4048 // held as the refit it leaves the lengthscales where the previous
4049 // data put them and the band relaxes on a stale model (Baker
4050 // 12_ethane: magnitude decayed from 0.67 to 0.27 over 120 outers
4051 // and the cell timed out). The optimizer's own tolerance decides
4052 // when the objective is stationary.
4053 bool newton_accepted = false;
4054 if (std::isfinite(shift_norm) && std::isfinite(energy_reference) &&
4055 shift.size() == theta_reference.size() && shift.allFinite()) {
4056 const Eigen::VectorXd theta_trial = theta_reference - shift;
4057 double energy_trial = std::numeric_limits<double>::quiet_NaN();
4058 Eigen::VectorXd grad_trial =
4059 Eigen::VectorXd::Zero(theta_trial.size());
4060 EnergyAndGradient eg_trial(energy_trial, grad_trial);
4061 // The trial is judged on the objective the reference was
4062 // measured on; the parameters it maps to must be finite and
4063 // positive (a secant step scaled by a wild curvature estimate
4064 // can send log-parameters past the exponent range, which
4065 // setParameters rejects: 01_hcn aborted there).
4066 bool trial_ok = theta_trial.allFinite();
4067 if (trial_ok) {
4069 theta_trial, opt_R_matrix, opt_R_indices, opt_y, eg_trial);
4070 }
4071 if (trial_ok && std::isfinite(energy_trial) &&
4072 grad_trial.allFinite() && energy_trial < energy_reference) {
4073 Eigen::VectorXd theta_accepted = theta_trial;
4074 leaveOptimizationObjectiveFrame(objective_frame,
4075 &theta_accepted);
4076 bool applied = theta_accepted.allFinite();
4077 if (applied) {
4078 try {
4079 setParameters(theta_accepted);
4080 } catch (const std::invalid_argument&) {
4081 applied = false;
4082 }
4083 }
4084 if (!applied) {
4085 // Re-enter the frame so the refit branch below can
4086 // leave it and restore the raw parameters.
4087 objective_frame = enterOptimizationObjectiveFrame(
4088 opt_y, fit_observation.E.size(), &theta_reference);
4089 }
4090 newton_accepted = applied;
4091 if (report_level >= 1) {
4092 log_man
4093 << "Objective warm start: ||H^-1 g_new||=" << shift_norm
4094 << " >= " << skip_threshold << ", objective "
4095 << energy_reference << " -> " << energy_trial << ".\n";
4096 }
4097 }
4098 }
4099 if (!newton_accepted) {
4100 leaveOptimizationObjectiveFrame(objective_frame, &theta_reference);
4101 setParameters(raw_theta);
4102 if (report_level >= 1) {
4103 log_man << "Objective refit: ||H^-1 g_new||=" << shift_norm
4104 << " >= " << skip_threshold << ".\n";
4105 }
4106 last_refit_kind_ = 2;
4107 return false;
4108 }
4109 // The caller runs the optimizer from the warm-started parameters.
4110 last_refit_kind_ = 1;
4111 return false;
4112 }
4113 leaveOptimizationObjectiveFrame(objective_frame, &theta_reference);
4114 setParameters(raw_theta);
4115 if (report_level >= 1) {
4116 log_man << "Objective fixed-theta refresh: ||H^-1 g_new||="
4117 << shift_norm << " < " << skip_threshold << ".\n";
4118 }
4119 last_refit_kind_ = 0;
4120 updateModelWithFullData(full_observation);
4122}
bool objectiveStationaritySkipMayBeActive() const noexcept
bool usesFullObservationForHyperparameterOptimization(const Observation &observation) const noexcept
bool evaluateNlmlHessianVector(const Eigen::VectorXd &x_ind, const EigenMatrix &x, const Eigen::VectorXd &y, const Eigen::VectorXd &direction, Eigen::VectorXd &product, const TrainingKernelGeometry *training_geom=nullptr)
Exact Hessian-vector product of the negative log marginal likelihood, including the covariance-functi...
Definition Hessian.cpp:371
bool exceedsThreshold(double value, double threshold) noexcept

◆ refreshLengthScaleLeaders()

void gpr::GaussianProcessRegression::refreshLengthScaleLeaders ( )

Recomputes the leaders from the released flags.

Definition at line 713 of file GaussianProcessRegression.cpp.

714{
715 auto& ties = length_scale_ties_;
716 if (!ties.valid) return;
717 // Index_t is unsigned: the count itself marks a base without a leader.
718 const Index_t none = ties.count();
719 ties.leader.assign(ties.parent.size(), none);
720 std::vector<Index_t> first(static_cast<std::size_t>(ties.base_count), none);
721 for (std::size_t t = 0; t < ties.parent.size(); ++t) {
722 if (ties.released[t]) {
723 ties.leader[t] = static_cast<Index_t>(t);
724 continue;
725 }
726 auto& lead = first[static_cast<std::size_t>(ties.parent[t])];
727 if (lead == none) lead = static_cast<Index_t>(t);
728 ties.leader[t] = lead;
729 }
730 // The covariance function's own prior counts each group once.
731 if (sexpat_cov_func != nullptr && use_length_scale_ties_) {
732 Eigen::VectorXd weight(ties.count());
733 for (Index_t t = 0; t < ties.count(); ++t)
734 weight(t) = ties.leader[t] == t ? 1.0 : 0.0;
735 sexpat_cov_func->setLengthScalePriorWeights(weight);
736 }
737}

◆ refreshVariancePrefactor()

virtual void gpr::GaussianProcessRegression::refreshVariancePrefactor ( const Eigen::VectorXd & )
inlinevirtual

Hook called inside calculateVarianceLaplace at each CCD grid point, right after calculateMeanPrediction (so b := L^{-1} y is valid) and before calculateVariance(scratch_var). Purpose: let subclasses refresh any hyperparameter-dependent cached scalar that their override of calculateVariance consumes.

Default: no-op. StudentTProcessRegression overrides this to recompute tp_prefactor_ = (2 hp_b + S) / (2 hp_a + n - 2) per grid point so the mixture variance reflects the TP's full hyperparameter posterior (the MAP prefactor is stale at every off-centre CCD point).

Reimplemented in gpr::StudentTProcessRegression.

Definition at line 3980 of file GaussianProcessRegression.h.

3980 {
3981 }

◆ releaseFitGeometry()

void gpr::GaussianProcessRegression::releaseFitGeometry ( ) const
noexcept

Definition at line 1848 of file CovarianceAssembly.cpp.

1849{
1850 fit_geometry_cache_.clear();
1851 fit_geometry_cache_rows_.resize(0, 0);
1852 fit_geometry_cache_indices_.resize(0);
1853 fit_geometry_cache_conf_ = AtomsConfiguration{};
1854 fit_geometry_cache_pair_local_ = false;
1855 fit_geometry_cache_far_field_radius_ = 0.0;
1856 fit_geometry_cache_grid_ = {};
1857}

◆ releaseLengthScaleTieForTesting()

void gpr::GaussianProcessRegression::releaseLengthScaleTieForTesting ( Index_t member)
inline

Gives the tie member its own length scale, as the evidence screen does once it has accumulated enough.

Definition at line 1883 of file GaussianProcessRegression.h.

1884 {
1885 length_scale_ties_.released.at(static_cast<std::size_t>(member)) = true;
1887 }

◆ releaseTrainingKokkosFactor()

void gpr::GaussianProcessRegression::releaseTrainingKokkosFactor ( )
protected

Definition at line 217 of file Decompose.cpp.

218{
219#ifdef GPR_LINALG_KOKKOS
221 device_posterior_.reset();
222#endif
223}

◆ removeColumn()

void gpr::GaussianProcessRegression::removeColumn ( const Index_t column_ind,
EigenMatrix & matrix )

Remove column from the dense matrix.

Parameters
column_indColumn index
matrixDense matrix

Definition at line 2833 of file CovarianceAssembly.cpp.

2835{
2836 // Index_t is unsigned, so cols() - 1 on an empty matrix wraps to
2837 // 4294967295 and feeds that to block() and conservativeResize().
2838 if (matrix.cols() == 0) return;
2839 const Eigen::Index num_rows = matrix.rows();
2840 const Eigen::Index num_cols = matrix.cols() - 1;
2841 const Eigen::Index ind = static_cast<Eigen::Index>(column_ind);
2842 if (ind > num_cols) return;
2843
2844 if (ind < num_cols)
2845 matrix.block(0, ind, num_rows, num_cols - ind) =
2846 matrix.block(0, ind + 1, num_rows, num_cols - ind);
2847
2848 matrix.conservativeResize(num_rows, num_cols);
2849}

◆ reportedVarianceCalibrationFactor()

double gpr::GaussianProcessRegression::reportedVarianceCalibrationFactor ( ) const
inlinenodiscardnoexcept

Definition at line 2885 of file GaussianProcessRegression.h.

2886 {
2887 return hssvd_variance_calibration_factor_;
2888 }

◆ requiresScgFallbackImprovement()

bool gpr::GaussianProcessRegression::requiresScgFallbackImprovement ( ) const
nodiscardnoexcept

Definition at line 5128 of file Optimize.cpp.

5129{
5130 return optimizer_state_->require_scg_fallback_improvement;
5131}

◆ resetDispatchedMapMeanHessianActionsForTesting()

void gpr::GaussianProcessRegression::resetDispatchedMapMeanHessianActionsForTesting ( ) const
noexcept

Reset the count of exact MAP Hessian actions built by dispatch.

Definition at line 155 of file GaussianProcessRegression.cpp.

157{
158 optimizer_state_->mean_hessian.dispatched_map_hessian_actions = 0;
159}

◆ resetDistributedHssvdDualKernelAssemblyCallsForTesting()

void gpr::GaussianProcessRegression::resetDistributedHssvdDualKernelAssemblyCallsForTesting ( ) const
inlinenoexcept

Definition at line 2970 of file GaussianProcessRegression.h.

2971 {
2972 distributed_hssvd_dual_kernel_assemblies_for_testing_ = 0;
2973 }

◆ resetDistributedHssvdDualKernelFactorizationCallsForTesting()

void gpr::GaussianProcessRegression::resetDistributedHssvdDualKernelFactorizationCallsForTesting ( ) const
inlinenoexcept

Definition at line 2979 of file GaussianProcessRegression.h.

2981 {
2982 distributed_hssvd_dual_kernel_factorizations_for_testing_ = 0;
2983 }

◆ resetDistributedTrainingCovarianceAssemblyCallsForTesting()

void gpr::GaussianProcessRegression::resetDistributedTrainingCovarianceAssemblyCallsForTesting ( ) const
inlinenoexcept

Definition at line 3140 of file GaussianProcessRegression.h.

3142 {
3143 distributed_training_covariance_assemblies_for_testing_ = 0;
3144 }

◆ resetFullDataRebuildCountersForTesting()

void gpr::GaussianProcessRegression::resetFullDataRebuildCountersForTesting ( ) const
inlinenoexcept

Definition at line 2798 of file GaussianProcessRegression.h.

2799 {
2800 full_data_rebuilds_for_testing_ = 0;
2801 }

◆ resetHssvdAppendCountersForTesting()

void gpr::GaussianProcessRegression::resetHssvdAppendCountersForTesting ( ) const
inlinenoexcept

Definition at line 2781 of file GaussianProcessRegression.h.

2782 {
2783 hssvd_append_updates_for_testing_ = 0;
2784 }

◆ resetHssvdFactorizationCountersForTesting()

void gpr::GaussianProcessRegression::resetHssvdFactorizationCountersForTesting ( ) const
inlinenoexcept

Definition at line 2789 of file GaussianProcessRegression.h.

2790 {
2791 hssvd_full_factorizations_for_testing_ = 0;
2792 distributed_hssvd_dual_kernel_factorizations_for_testing_ = 0;
2793 }

◆ resetHssvdHessianVectorCallsForTesting()

void gpr::GaussianProcessRegression::resetHssvdHessianVectorCallsForTesting ( ) const
inlinenoexcept

Definition at line 1666 of file GaussianProcessRegression.h.

1667 {
1668 hssvd_hessian_vector_calls_for_testing_ = 0;
1669 }

◆ resetIncrementalCholeskyCountersForTesting()

void gpr::GaussianProcessRegression::resetIncrementalCholeskyCountersForTesting ( ) const
inlinenoexcept

Definition at line 2690 of file GaussianProcessRegression.h.

2691 {
2692 incremental_cholesky_updates_for_testing_ = 0;
2693 full_cholesky_factorizations_for_testing_ = 0;
2694 serial_factor_reuses_for_testing_ = 0;
2695 }

◆ resetLaplaceMeanBlockPartitionCallsForTesting()

void gpr::GaussianProcessRegression::resetLaplaceMeanBlockPartitionCallsForTesting ( ) const
inlinenoexcept

Definition at line 2681 of file GaussianProcessRegression.h.

2682 {
2683 laplace_mean_block_partition_calls_for_testing_ = 0;
2684 }

◆ resetLaplacePosteriorSignatureBuildsForTesting()

void gpr::GaussianProcessRegression::resetLaplacePosteriorSignatureBuildsForTesting ( ) const
inlinenoexcept

Definition at line 2658 of file GaussianProcessRegression.h.

2659 {
2660 laplace_posterior_signature_builds_for_testing_ = 0;
2661 }

◆ resetLeaveOneOutObjectiveEvaluationsForTesting()

void gpr::GaussianProcessRegression::resetLeaveOneOutObjectiveEvaluationsForTesting ( ) const
inlinenoexcept

Definition at line 2938 of file GaussianProcessRegression.h.

2939 {
2940 leave_one_out_objective_evaluations_for_testing_ = 0;
2941 }

◆ resetLocalLooObjectiveEvaluationsForTesting()

void gpr::GaussianProcessRegression::resetLocalLooObjectiveEvaluationsForTesting ( ) const
inlinenoexcept

Definition at line 2947 of file GaussianProcessRegression.h.

2948 {
2949 local_loo_objective_evaluations_for_testing_ = 0;
2950 }

◆ resetProfileSplitTotals()

void gpr::GaussianProcessRegression::resetProfileSplitTotals ( )
inlinenoexcept

Definition at line 1544 of file GaussianProcessRegression.h.

1545 {
1546 profile_split_totals_ = {};
1547 }

◆ residentTrainingFactorRetainedForTesting()

bool gpr::GaussianProcessRegression::residentTrainingFactorRetainedForTesting ( ) const
inlinenodiscardnoexcept

True while a Kokkos copy of the training factor is retained beside L. Host execution memory keeps the single Eigen factor and leaves this false. Device memory retains the copy.

Definition at line 2727 of file GaussianProcessRegression.h.

2728 {
2729#ifdef GPR_LINALG_KOKKOS
2730 return static_cast<bool>(resident_training_factor_);
2731#else
2732 return false;
2733#endif
2734 }

◆ residualConfigurationCount()

Eigen::Index gpr::GaussianProcessRegression::residualConfigurationCount ( ) const
inlinenodiscardnoexcept

Definition at line 648 of file GaussianProcessRegression.h.

649 {
650 return last_residual_configuration_count_;
651 }

◆ residualInducingCount()

Eigen::Index gpr::GaussianProcessRegression::residualInducingCount ( ) const
inlinenodiscardnoexcept

Configurations carrying the environment residual process in the last residual fit, and how many configurations that fit covered. Equal counts mean the fit was the exact model; a smaller inducing count means the residual prior was the Nystrom projection onto those configurations with each configuration's own block restored, so single-geometry variances stayed exact.

Definition at line 644 of file GaussianProcessRegression.h.

645 {
646 return last_residual_inducing_count_;
647 }

◆ restoreActivePosterior()

bool gpr::GaussianProcessRegression::restoreActivePosterior ( const ActivePosteriorRestorePoint & point,
const Observation & full_observation )
nodiscard

Recondition the retained correction after restoring its background parameters and output coordinates. False denotes an empty restore point; incompatible ownership, coordinates, or observations throw.

Definition at line 920 of file ActivePosterior.cpp.

923{
924 if (!point.state_) return false;
925 const auto& saved = *point.state_;
926 if (saved.owner != this || saved.posterior->output_mean != y_mean_ ||
927 saved.posterior->output_scale != y_scale_ ||
928 saved.posterior->hssvd != use_hssvd_backend_ ||
929 !hasFullFitPrefix(full_observation, saved.background)) {
930 throw std::invalid_argument(
931 "active posterior restoration requires its owning model, output "
932 "coordinates, and full-fit prefix");
933 }
934 updateModelWithFullData(saved.background);
935 if (!reconditionActivePosterior(full_observation, *saved.posterior)) {
936 throw std::runtime_error(
937 "retained active posterior could not be conditioned");
938 }
939 return true;
940}

◆ restoreAtomicEnvironmentParameterState()

void gpr::GaussianProcessRegression::restoreAtomicEnvironmentParameterState ( const AtomicEnvironmentParameterState & state)

Restore the atomic parameter domain and invalidate its conditioning. The caller rebuilds the posterior on the observations it retains.

Definition at line 288 of file AtomicEnvironment.cpp.

290{
291 if (state.enabled && state.theta.size() > 0) {
292 if (state.species.empty() ||
293 state.theta.size() !=
294 static_cast<Eigen::Index>(state.species.size()) + 3 ||
295 !state.theta.allFinite() || state.species.front() <= 0 ||
296 !std::is_sorted(state.species.begin(), state.species.end()) ||
297 std::adjacent_find(state.species.begin(), state.species.end()) !=
298 state.species.end())
299 throw std::invalid_argument("invalid atomic parameter state");
300 for (Eigen::Index index = 0; index < state.theta.size(); ++index) {
301 const double value = std::exp(state.theta(index));
302 if (!(value > 0.0) || !std::isfinite(value))
303 throw std::invalid_argument("invalid atomic parameter scale");
304 }
305 } else if (state.enabled && !state.species.empty()) {
306 throw std::invalid_argument("incomplete atomic parameter state");
307 }
308 setAtomicEnvironmentModel(state.enabled);
309 if (!state.enabled) return;
310 invalidateLikelihoodNoiseDependentState();
311 atomic_environment_parameter_species_ = state.species;
312 atomic_environment_parameters_ = state.theta;
313}
void setAtomicEnvironmentModel(bool enabled)

◆ restoreLengthScaleFitState()

void gpr::GaussianProcessRegression::restoreLengthScaleFitState ( const LengthScaleFitState & state)

Definition at line 662 of file GaussianProcessRegression.cpp.

664{
665 if (length_scale_ties_ == state.ties &&
666 use_length_scale_ties_ == state.enabled)
667 return;
668 if (state.ties.valid &&
669 (state.ties.parent != atoms_config.pair_type_parent ||
670 state.ties.base_count != atoms_config.n_base_pt)) {
671 throw std::invalid_argument(
672 "length-scale fit state requires the same chemical pair types");
673 }
674 length_scale_ties_ = state.ties;
675 use_length_scale_ties_ = state.enabled;
676 if (sexpat_cov_func)
677 sexpat_cov_func->setLengthScalePriorWeights(Eigen::VectorXd());
679 ++laplace_model_revision_;
680 laplace_posterior_.reset();
681 // Curvature pairs are expressed in the parameter groups of their fit.
683}

◆ restoreOutputTransform()

void gpr::GaussianProcessRegression::restoreOutputTransform ( double mean,
double scale,
bool frozen_mean )

Restore output coordinates alongside a kernel represented in them.

Definition at line 2094 of file GaussianProcessRegression.cpp.

2097{
2098 if (!std::isfinite(mean) || !std::isfinite(scale) || !(scale > 0.0)) {
2099 throw std::invalid_argument(
2100 "GP output transform requires a finite mean and positive scale");
2101 }
2102 if (y_mean_ == mean && y_scale_ == scale && y_mean_frozen_ == frozen_mean) {
2103 return;
2104 }
2105
2106 y_mean_ = mean;
2107 y_scale_ = scale;
2108 y_mean_frozen_ = frozen_mean;
2109 invalidateLikelihoodNoiseDependentState();
2110}

◆ restoreSecantQuadraticPrior()

void gpr::GaussianProcessRegression::restoreSecantQuadraticPrior ( const SecantQuadraticPriorState & state)

Reinstall a retained quadratic. The use counter is a running tally of what this model evaluated, not part of the quadratic, so it keeps every use made while another quadratic was installed.

Definition at line 842 of file GaussianProcessRegression.cpp.

844{
845 if (!state.active) {
847 return;
848 }
849 setSecantQuadraticPrior(state.position, state.gradient, state.hessian,
850 state.energy);
851}
void setSecantQuadraticPrior(const Eigen::VectorXd &position, const Eigen::VectorXd &gradient, const Eigen::MatrixXd &hessian, double reference_energy)

◆ retainActivePosterior()

GaussianProcessRegression::ActivePosteriorRestorePoint gpr::GaussianProcessRegression::retainActivePosterior ( ) const
nodiscard

Definition at line 909 of file ActivePosterior.cpp.

910{
912 if (active_posterior_) {
913 point.state_ = std::make_shared<ActivePosteriorRestorePoint::State>(
914 ActivePosteriorRestorePoint::State{this, full_fit_observations_,
915 active_posterior_});
916 }
917 return point;
918}

◆ retainHyperparameterPosterior()

GaussianProcessRegression::HyperparameterPosterior gpr::GaussianProcessRegression::retainHyperparameterPosterior ( )
nodiscard

Materialize and retain the EB/Laplace hyperparameter distribution. Other uncertainty modes return an empty quadrature.

Definition at line 83 of file HyperparameterPosterior.cpp.

84{
85 if ((uncertainty_mode_ != UncertaintyMode::EB &&
86 uncertainty_mode_ != UncertaintyMode::LAPLACE) ||
87 !ensureLaplacePosterior())
88 return {};
90}
HyperparameterPosterior currentHyperparameterPosterior() const
Retain an existing, current quadrature without estimating a new one.

◆ retainSecantQuadraticPrior()

GaussianProcessRegression::SecantQuadraticPriorState gpr::GaussianProcessRegression::retainSecantQuadraticPrior ( ) const
nodiscard

Definition at line 835 of file GaussianProcessRegression.cpp.

836{
837 return {secant_quadratic_prior_active_, secant_reference_position_,
838 secant_reference_gradient_, secant_hessian_,
839 secant_reference_energy_};
840}

◆ retainsFittedHyperparameterDensity()

bool gpr::GaussianProcessRegression::retainsFittedHyperparameterDensity ( ) const
inlinenodiscardnoexcept

Definition at line 4081 of file GaussianProcessRegression.h.

4082 {
4083 return retain_fitted_hyperparameter_density_;
4084 }

◆ retainTrainingCholeskyFactor()

void gpr::GaussianProcessRegression::retainTrainingCholeskyFactor ( )
protected

Definition at line 225 of file Decompose.cpp.

226{
227#ifdef GPR_LINALG_KOKKOS
228 // Host execution memory already holds the factor in L. Copying it into
229 // a KokkosFactor makes every later solve, whiten and log determinant
230 // skip BackendContext's in-place Eigen kernels. One check here covers
231 // every caller. Device memory keeps the copy. Either way a previous
232 // device posterior is released, so a query never sees a posterior
233 // whose resident factor is null.
236 return;
237 }
238 device_posterior_.reset();
239 resident_training_factor_ = std::make_shared<linalg::KokkosFactor>(L);
240#endif
241}
bool kokkosHostExecutionMemory() noexcept

◆ rffFeatureSelection()

const RFFFeatureSelection & gpr::GaussianProcessRegression::rffFeatureSelection ( ) const
inlinenodiscardnoexcept

Definition at line 2233 of file GaussianProcessRegression.h.

2235 {
2236 return rff_selection_;
2237 }

◆ rffFeatureSelectionAuto()

bool gpr::GaussianProcessRegression::rffFeatureSelectionAuto ( ) const
inlinenodiscardnoexcept

Definition at line 2219 of file GaussianProcessRegression.h.

2220 {
2221 return rff_auto_;
2222 }

◆ rffForceTolFraction()

double gpr::GaussianProcessRegression::rffForceTolFraction ( ) const
inlinenodiscardnoexcept

Definition at line 2223 of file GaussianProcessRegression.h.

2224 {
2225 return rff_force_tol_fraction_;
2226 }

◆ rgminInitialLogMove()

double gpr::GaussianProcessRegression::rgminInitialLogMove ( ) const
inlinenodiscardnoexcept

Definition at line 2472 of file GaussianProcessRegression.h.

2473 {
2474 return rgmin_initial_log_move_;
2475 }

◆ rgminWarmPairsForTesting()

std::size_t gpr::GaussianProcessRegression::rgminWarmPairsForTesting ( ) const
nodiscardnoexcept

Curvature pairs the last rgmin fit transplanted from that record.

Definition at line 3623 of file Optimize.cpp.

3624{
3625 if (optimizer_state_ == nullptr) return 0;
3626 std::size_t pairs = optimizer_state_->scg_alternative.warmPairs();
3627 std::visit(
3628 [&](const auto& optimizer) {
3629 using Optimizer = std::decay_t<decltype(optimizer)>;
3630 if constexpr (std::is_same_v<Optimizer, funcmin::RgminOpt>)
3631 pairs += optimizer.warmPairs();
3632 },
3633 optimizer_state_->optimizer);
3634 return pairs;
3635}

◆ rgminWarmStartsForTesting()

std::size_t gpr::GaussianProcessRegression::rgminWarmStartsForTesting ( ) const
nodiscardnoexcept

Fits the rgmin sessions opened with the previous fit's record.

Definition at line 3608 of file Optimize.cpp.

3610{
3611 if (optimizer_state_ == nullptr) return 0;
3612 std::size_t warm = optimizer_state_->scg_alternative.warmStarts();
3613 std::visit(
3614 [&](const auto& optimizer) {
3615 using Optimizer = std::decay_t<decltype(optimizer)>;
3616 if constexpr (std::is_same_v<Optimizer, funcmin::RgminOpt>)
3617 warm += optimizer.warmStarts();
3618 },
3619 optimizer_state_->optimizer);
3620 return warm;
3621}

◆ rigidDeflationDiagnostic()

const RigidDeflationDiagnostic & gpr::GaussianProcessRegression::rigidDeflationDiagnostic ( ) const
inlinenodiscardnoexcept

Definition at line 1588 of file GaussianProcessRegression.h.

1590 {
1591 return rigid_deflation_diag_;
1592 }

◆ rigidNoiseDerivatives()

std::pair< double, double > gpr::GaussianProcessRegression::rigidNoiseDerivatives ( const Eigen::VectorXd & direction) const
nodiscardprotected

First and second derivatives of the learned likelihood noise variance along direction: the rigid-block covariance derivatives of the rigid-null deflated objective, whose rigid block is noise alone.

Definition at line 73 of file Hessian.cpp.

75{
76 const double noise = likelihoodNoiseVariance();
77 if (direction.size() <= covarianceParameterCount() || !(noise > 0.0))
78 return {0.0, 0.0};
79 const double noise_direction = direction(direction.size() - 1);
80 return {noise * noise_direction, noise * noise_direction * noise_direction};
81}

◆ rigidNullDeflationEnabled()

bool gpr::GaussianProcessRegression::rigidNullDeflationEnabled ( ) const
inlinenodiscardnoexcept

Definition at line 1584 of file GaussianProcessRegression.h.

1585 {
1587 }

◆ robustExtraNoiseForTesting()

const Eigen::VectorXd & gpr::GaussianProcessRegression::robustExtraNoiseForTesting ( ) const
inlinenodiscardnoexcept

Definition at line 1835 of file GaussianProcessRegression.h.

1837 {
1838 return robust_extra_;
1839 }

◆ robustNu()

double gpr::GaussianProcessRegression::robustNu ( ) const
inlinenodiscardnoexcept

Definition at line 1821 of file GaussianProcessRegression.h.

1822 {
1823 return robust_nu_;
1824 }

◆ robustResidualNormsForTesting()

const Eigen::VectorXd & gpr::GaussianProcessRegression::robustResidualNormsForTesting ( ) const
inlinenodiscardnoexcept

Definition at line 1830 of file GaussianProcessRegression.h.

1832 {
1833 return robust_z2_;
1834 }

◆ rowsInTrainingFactorLayout()

EigenMatrix gpr::GaussianProcessRegression::rowsInTrainingFactorLayout ( const EigenMatrix & input) const
nodiscard

Definition at line 631 of file GaussianProcessRegression.cpp.

633{
634 return permuteTrainingRows(input);
635}

◆ samplePhysicalPriorMean()

bool gpr::GaussianProcessRegression::samplePhysicalPriorMean ( const Eigen::VectorXd & position,
double & energy,
Eigen::VectorXd & gradient ) const

Exact energy and Cartesian gradient of that prior. False when neither prior is active.

Definition at line 853 of file GaussianProcessRegression.cpp.

856{
857 if (position.size() == 0 || !position.allFinite())
858 throw std::invalid_argument(
859 "secant quadratic mean requires a finite geometry");
860 const auto accept = [&](double prior_energy,
861 const Eigen::RowVectorXd& prior_gradient,
862 const char* name) {
863 if (prior_gradient.size() != position.size() ||
864 !std::isfinite(prior_energy) || !prior_gradient.allFinite())
865 throw std::runtime_error(std::string(name) +
866 " prior mean has no finite gradient for "
867 "the secant");
868 energy = prior_energy;
869 gradient = prior_gradient.transpose();
870 };
871 if (ffPriorMeanActive()) {
872 const auto evaluation = ff_prior_mean_->evaluate(position.transpose());
873 accept(evaluation.energy, evaluation.gradient, "Morse");
874 return true;
875 }
876 if (zblPriorMeanActive()) {
877 const auto evaluation = zbl_prior_mean_->evaluate(position.transpose());
878 accept(evaluation.energy, evaluation.gradient, "ZBL");
879 return true;
880 }
881 return false;
882}

◆ scaleLaplaceFactorForTesting()

bool gpr::GaussianProcessRegression::scaleLaplaceFactorForTesting ( std::size_t index,
double scale )

Multiplies the Cholesky factor of Laplace factor index by scale on the rank that owns it, building the posterior first. A scale far below 1 inflates the whitened cross covariance, so the stable variance of that factor is negative and is refused. Returns whether this rank owned and rescaled the factor.

Definition at line 1061 of file LaplacePosterior.cpp.

1063{
1064 if (!ensureLaplacePosterior() ||
1065 index >= laplace_posterior_->factors.size())
1066 return false;
1067 auto& factor = laplace_posterior_->factors[index];
1068 if (!factor.owned || !factor.valid) return false;
1069 factor.L *= scale;
1070 return true;
1071}

◆ scaleTrainingVarianceToPhysical()

void gpr::GaussianProcessRegression::scaleTrainingVarianceToPhysical ( Eigen::Ref< Eigen::VectorXd > variance) const

Definition at line 2430 of file Decompose.cpp.

2432{
2433 const double y_scale = y_scale_;
2434 const double calibration = hssvd_variance_calibration_factor_;
2435 if (!std::isfinite(y_scale) || !(y_scale > 0.0))
2436 throw std::domain_error(
2437 "training variance scaling needs a finite positive output scale");
2438 if (!std::isfinite(calibration) || !(calibration > 0.0))
2439 throw std::domain_error(
2440 "training variance scaling needs a finite positive calibration "
2441 "factor");
2442 const double factor = y_scale * y_scale * calibration;
2443 const bool normal_factor =
2444 std::isfinite(factor) && factor >= std::numeric_limits<double>::min();
2445 for (Eigen::Index i = 0; i < variance.size(); ++i) {
2446 const double value = variance(i);
2447 if (std::isinf(value) && value > 0.0) continue;
2448 variance(i) = normal_factor ? value * factor
2449 : value * y_scale * y_scale * calibration;
2450 }
2451}

◆ scgStalledForTesting()

bool gpr::GaussianProcessRegression::scgStalledForTesting ( ) const
inlinenodiscardnoexcept

Definition at line 2632 of file GaussianProcessRegression.h.

2633 {
2634 return scg_stalled_;
2635 }

◆ secantQuadraticHessian()

const Eigen::MatrixXd & gpr::GaussianProcessRegression::secantQuadraticHessian ( ) const
nodiscard

Definition at line 884 of file GaussianProcessRegression.cpp.

885{
886 if (!secant_quadratic_prior_active_)
887 throw std::logic_error("secant quadratic mean is not active");
888 return secant_hessian_;
889}

◆ secantQuadraticPriorActive()

bool gpr::GaussianProcessRegression::secantQuadraticPriorActive ( ) const
inlinenodiscardnoexcept

Definition at line 2021 of file GaussianProcessRegression.h.

2022 {
2023 return secant_quadratic_prior_active_;
2024 }

◆ secantQuadraticPriorUses()

int gpr::GaussianProcessRegression::secantQuadraticPriorUses ( ) const
inlinenodiscardnoexcept

Definition at line 2017 of file GaussianProcessRegression.h.

2018 {
2019 return secant_quadratic_prior_uses_;
2020 }

◆ selectOptimizationSubset()

Observation gpr::GaussianProcessRegression::selectOptimizationSubset ( const Observation & full_observation) const
protected

Select a hyperparameter-optimization subset via FPS-EMD.

FPS-EMD (Goswami & Jonsson, ChemPhysChem 27 (2025), doi:10.1002/cphc.202500730) is a hyperparameter subset: full X stays for prediction. Keep fps_options.latest_points (default 2) most recent observations, then greedy-maximin the remainder of fps_options.history on fps_options.metric (default EMD). The force_threshold gate is +inf and does not drop points.

Parameters
full_observationThe complete set of observations.
Returns
An Observation object containing the selected subset.

Definition at line 1490 of file Optimize.cpp.

1492{
1493 Observation optimization_observation;
1494 const int num_total_points = full_observation.R.rows();
1495 const bool energy_is_row_vector =
1496 full_observation.E.rows() == 1 &&
1497 full_observation.E.cols() == num_total_points;
1498 const std::vector<int> selected_indices =
1499 selectOptimizationSubsetRows(full_observation);
1500 const int num_final = selected_indices.size();
1501 optimization_observation.R.resize(num_final, full_observation.R.cols());
1502 optimization_observation.R.setZero();
1503 if (energy_is_row_vector) {
1504 optimization_observation.E.resize(1, num_final);
1505 } else {
1506 optimization_observation.E.resize(num_final, full_observation.E.cols());
1507 }
1508 optimization_observation.E.setZero();
1509 optimization_observation.G.resize(num_final, full_observation.G.cols());
1510 optimization_observation.G.setZero();
1511 for (int i = 0; i < num_final; ++i) {
1512 const int idx = selected_indices[i];
1513 optimization_observation.R.row(i) = full_observation.R.row(idx);
1514 if (energy_is_row_vector) {
1515 optimization_observation.E(0, i) = full_observation.E(0, idx);
1516 } else {
1517 optimization_observation.E.row(i) = full_observation.E.row(idx);
1518 }
1519 optimization_observation.G.row(i) = full_observation.G.row(idx);
1520 }
1521 return optimization_observation;
1522}
std::vector< int > selectOptimizationSubsetRows(const Observation &full_observation) const
Select a hyperparameter-optimization subset via FPS-EMD.

◆ selectOptimizationSubsetRows()

std::vector< int > gpr::GaussianProcessRegression::selectOptimizationSubsetRows ( const Observation & full_observation) const
protected

Select a hyperparameter-optimization subset via FPS-EMD.

Rows selectOptimizationSubset would keep, in ascending order: the same latest-points-plus-FPS choice, without copying the observation.

FPS-EMD (Goswami & Jonsson, ChemPhysChem 27 (2025), doi:10.1002/cphc.202500730) is a hyperparameter subset: full X stays for prediction. Keep fps_options.latest_points (default 2) most recent observations, then greedy-maximin the remainder of fps_options.history on fps_options.metric (default EMD). The force_threshold gate is +inf and does not drop points.

Parameters
full_observationThe complete set of observations.
Returns
The kept rows of full_observation, in ascending order.

Definition at line 1270 of file Optimize.cpp.

1272{
1273 ScopedPhaseTimer subset_timer(PhaseTimers::subset_seconds);
1274 const int num_optimization_points = fps_options.history;
1275 const int num_latest_points = fps_options.latest_points;
1276 const int num_total_points = full_observation.R.rows();
1277 // TODO(rg): Make this a configurable parameter
1278 const double force_threshold = std::numeric_limits<double>::infinity();
1279 std::vector<int> valid_indices;
1280 valid_indices.reserve(num_total_points);
1281 std::vector<int> required_indices;
1282 const bool have_required =
1283 optimization_required_positions_.cols() == full_observation.R.cols();
1284
1285 const bool pooled =
1286 static_cast<int>(optimization_row_pool_.size()) == num_total_points;
1287 for (int i = 0; i < num_total_points; ++i) {
1288 bool required = false;
1289 if (have_required)
1290 for (Eigen::Index row = 0;
1291 row < optimization_required_positions_.rows(); ++row)
1292 if ((full_observation.R.row(i).array() ==
1293 optimization_required_positions_.row(row).array())
1294 .all()) {
1295 required = true;
1296 break;
1297 }
1298 if (!required && pooled &&
1299 !optimization_row_pool_[static_cast<std::size_t>(i)])
1300 continue;
1301 double max_force = 0.0;
1302 bool finite_force = true;
1303 for (int j = 0; j < full_observation.G.cols(); ++j) {
1304 const double component = full_observation.G(i, j);
1305 if (!std::isfinite(component)) {
1306 finite_force = false;
1307 break;
1308 }
1309 max_force = std::max(max_force, std::abs(component));
1310 }
1311 if (finite_force && max_force < force_threshold) {
1312 valid_indices.push_back(i);
1313 if (required) required_indices.push_back(i);
1314 }
1315 }
1316
1317 const int num_valid_points = valid_indices.size();
1318
1319 if (num_valid_points <= num_optimization_points) return valid_indices;
1320
1321 // --- Combined Latest + Farthest Point Sampling (FPS) on VALID points ---
1322 aux::Distance distance_calculator;
1323 std::vector<int> selected_indices = required_indices;
1324 std::unordered_set<int> selected_indices_set(required_indices.begin(),
1325 required_indices.end());
1326 const int actual_latest_points =
1327 std::min(num_latest_points, num_valid_points);
1328 const int subset_size =
1329 std::max({num_optimization_points, actual_latest_points,
1330 static_cast<int>(required_indices.size())});
1331
1332 // 1. Start with the 'num_latest_points' most recent *valid* points.
1333 for (int i = 0; i < actual_latest_points &&
1334 static_cast<int>(selected_indices.size()) < subset_size;
1335 ++i) {
1336 int current_idx = valid_indices[num_valid_points - 1 - i];
1337 if (selected_indices_set.insert(current_idx).second)
1338 selected_indices.push_back(current_idx);
1339 }
1340 const int num_fps_points_to_select =
1341 std::max(0, subset_size - static_cast<int>(selected_indices.size()));
1342
1343 if (num_fps_points_to_select > 0) {
1344 // --- FPS Implementation for the remaining points ---
1345 std::unordered_map<int, double> min_dists_map;
1346 const Eigen::Index n_cols = full_observation.R.cols();
1347
1348 // Pre-allocate reusable buffers outside loops
1349 FieldMatrixd candidate_coord(1, n_cols);
1350 FieldMatrixd ref_coord(1, n_cols);
1351 FieldMatrixd dist_matrix;
1352
1353 // Helper lambda to compute distance between two single-row coords
1354 auto compute_dist = [&](const FieldMatrixd& c1,
1355 const FieldMatrixd& c2) -> double {
1356 switch (fps_options.metric) {
1358 distance_calculator.dist_max1Dlog(
1359 c1, c2, this->atoms_config, dist_matrix);
1360 break;
1362 distance_calculator.dist_emd(c1, c2, this->atoms_config,
1363 dist_matrix);
1364 break;
1366 distance_calculator.dist_rmsd(c1, c2, this->atoms_config,
1367 dist_matrix);
1368 break;
1369 default:
1370 throw("Invalid distance metric for FPS.");
1371 }
1372 return dist_matrix(0, 0);
1373 };
1374
1375 // Initialize min_dists for all valid, unselected points
1376 for (int candidate_idx: valid_indices) {
1377 if (selected_indices_set.count(candidate_idx) == 0) {
1378 double current_min_dist = std::numeric_limits<double>::max();
1379 candidate_coord.row(0) = full_observation.R.row(candidate_idx);
1380
1381 for (int latest_idx: selected_indices) {
1382 ref_coord.row(0) = full_observation.R.row(latest_idx);
1383 current_min_dist =
1384 std::min(current_min_dist,
1385 compute_dist(candidate_coord, ref_coord));
1386 }
1387 min_dists_map[candidate_idx] = current_min_dist;
1388 }
1389 }
1390
1391 // 2. Iteratively select the remaining FPS points.
1392 for (int i = 0; i < num_fps_points_to_select; ++i) {
1393 std::vector<std::pair<int, double>> candidate_distances;
1394 candidate_distances.reserve(min_dists_map.size());
1395 for (auto const& [idx, dist]: min_dists_map) {
1396 candidate_distances.emplace_back(idx, dist);
1397 }
1398 const int farthest_point_idx =
1399 chooseFarthestPointDeterministic(candidate_distances);
1400
1401 if (farthest_point_idx != -1) {
1402 selected_indices.push_back(farthest_point_idx);
1403 selected_indices_set.insert(farthest_point_idx);
1404 min_dists_map.erase(farthest_point_idx);
1405
1406 ref_coord.row(0) = full_observation.R.row(farthest_point_idx);
1407
1408 for (auto& [candidate_idx, current_min_dist]: min_dists_map) {
1409 candidate_coord.row(0) =
1410 full_observation.R.row(candidate_idx);
1411 current_min_dist =
1412 std::min(current_min_dist,
1413 compute_dist(candidate_coord, ref_coord));
1414 }
1415 } else {
1416 break;
1417 }
1418 }
1419 }
1420
1421 std::sort(selected_indices.begin(), selected_indices.end());
1422 return selected_indices;
1423}
void dist_max1Dlog(const gpr::Coord &x1, const gpr::Coord &x2, const gpr::AtomsConfiguration &conf_info, gpr::FieldMatrixd &dist)
Give the maximum difference in the logarithmic inter-atomic distances between atomic configurations C...
Definition Distance.cpp:462
void dist_emd(const gpr::Coord &x1, const gpr::Coord &x2, const gpr::AtomsConfiguration &conf_info, gpr::FieldMatrixd &dist)
Calculates the Earth Mover's Distance between sets of configurations.
void dist_rmsd(const gpr::Coord &x1, const gpr::Coord &x2, const gpr::AtomsConfiguration &conf_info, gpr::FieldMatrixd &dist)
Calculates the aligned Root Mean Square Deviation (RMSD) between sets of configurations.
Definition Distance.cpp:410
static int chooseFarthestPointDeterministic(const std::vector< std::pair< int, double > > &candidate_distances, double tolerance=1e-12)

◆ selectRFFFeatures()

RFFFeatureSelection gpr::GaussianProcessRegression::selectRFFFeatures ( const Observation & observation,
std::uint64_t memory_cap_bytes = kRFFValidationMemoryCapBytes )
nodiscard

Choose D on observation without installing it. The production cap is kRFFValidationMemoryCapBytes. A smaller cap is only a test of the refusal path.

Definition at line 382 of file RFFSelection.cpp.

384{
385 auto reject = [this](RFFFeatureSelection report) -> RFFFeatureSelection {
386 report.accepted = false;
387 report.deferred = false;
388 report.features = 0;
389 report.status = "rejected";
390 if (report.detail.empty())
391 report.detail = "RFF feature selection failed";
392 rff_selection_ = report;
393 logRFFFeatureSelection(report);
394 throw RFFFeatureSelectionError(std::move(report));
395 };
396
397 RFFFeatureSelection report;
398 report.memory_cap_bytes = clampCapBytes(memory_cap_bytes);
399 report.force_convergence_tolerance = kRFFForceConvergenceTolerance;
400 const double nan = std::numeric_limits<double>::quiet_NaN();
401 report.max_energy_error = nan;
402 report.max_force_error = nan;
403 report.max_energy_oracle_error = nan;
404 report.max_force_oracle_error = nan;
405 report.exact_energy_oracle_error = nan;
406 report.exact_force_oracle_error = nan;
407
408 const bool valid_energy_vector =
409 observation.R.rows() == 0
410 ? observation.E.size() == 0
411 : (observation.E.size() == observation.R.rows() &&
412 (observation.E.rows() == 1 || observation.E.cols() == 1));
413 if (observation.R.rows() < 0 || observation.R.cols() <= 0 ||
414 observation.G.rows() != observation.R.rows() ||
415 observation.G.cols() != observation.R.cols() || !valid_energy_vector ||
416 !observation.R.allFinite() || !observation.E.allFinite() ||
417 !observation.G.allFinite()) {
418 report.detail =
419 "RFF feature selection requires finite coordinates and one finite "
420 "energy and matching gradient for every geometry";
421 return reject(std::move(report));
422 }
423 if (atomic_environment_model_) {
424 report.detail =
425 "RFF feature selection does not apply to the atomic-environment "
426 "model";
427 return reject(std::move(report));
428 }
429 if (!sexpat_cov_func || !const_cov_fun || !lik_gaussian) {
430 report.detail = "RFF feature selection requires an initialized GP";
431 return reject(std::move(report));
432 }
433 if (dynamic_cast<const StudentTProcessRegression*>(this) != nullptr) {
434 report.detail =
435 "RFF feature selection does not apply to the Student-t process";
436 return reject(std::move(report));
437 }
438 if (sexpat_cov_func->usesManifoldChart() ||
439 sexpat_cov_func->usesGeodesicHeatKernel()) {
440 report.detail =
441 "RFF feature selection requires the Cartesian Sexpat kernel";
442 return reject(std::move(report));
443 }
444 if (use_correction_) {
445 report.detail =
446 "RFF feature selection does not apply the corrected-noise "
447 "diagonal";
448 return reject(std::move(report));
449 }
450
451 const int n_geometries = static_cast<int>(observation.R.rows());
452 const int dimension = static_cast<int>(observation.R.cols());
453 const RFFValidationPlan plan =
454 planRFFFeatureValidation(n_geometries, dimension, memory_cap_bytes);
455 report.full_geometries = plan.full_geometries;
456 report.cartesian_dimension = plan.cartesian_dimension;
457 report.fit_geometries = plan.fit_geometries;
458 report.holdout_geometries = plan.holdout_geometries;
459 report.joint_rows = plan.joint_rows;
460 report.start_features = plan.feature_start;
461 report.limit_features = plan.feature_limit;
462 report.exact_gram_bytes = plan.exact_gram_bytes;
463 report.full_gram_bytes = plan.full_gram_bytes;
464
465 if (plan.deferred) {
466 report.deferred = true;
467 report.status = "deferred";
468 report.detail =
469 "RFF feature selection deferred: fewer than two geometries, "
470 "exact posterior retained";
471 rff_selection_ = report;
472 logRFFFeatureSelection(report);
473 return report;
474 }
475 if (!plan.admissible) {
476 report.detail =
477 "RFF feature selection refused: the memory cap cannot hold an "
478 "overdetermined exact posterior for even one fit geometry with "
479 "a hold-out (cap " +
480 std::to_string(memory_cap_bytes) + " bytes, full Gram " +
481 std::to_string(plan.full_gram_bytes) +
482 " bytes). No feature count was installed.";
483 return reject(std::move(report));
484 }
485
486 double energy_noise = 0.0;
487 double gradient_noise = 0.0;
488 rffObservationNoise(energy_noise, gradient_noise);
489 report.energy_noise = energy_noise;
490 report.gradient_noise = gradient_noise;
491 const double sigma_g = std::sqrt(gradient_noise);
492 const double sigma_e = std::sqrt(energy_noise);
493 if (!(sigma_g > 0.0) || !(sigma_g < kRFFForceConvergenceTolerance) ||
494 !(sigma_e > 0.0)) {
495 report.detail =
496 "RFF feature selection refused: the gradient noise standard "
497 "deviation " +
498 sci(sigma_g) + " eV/A is not strictly inside the force tolerance " +
500 " eV/A, so no fraction of that tolerance is decision-safe. No "
501 "feature count was installed.";
502 return reject(std::move(report));
503 }
504
505 double fraction = rff_force_tol_fraction_;
506 if (fraction == 0.0) fraction = sigma_g / kRFFForceConvergenceTolerance;
507 if (!(fraction > 0.0) || !(fraction < 1.0)) {
508 report.detail =
509 "RFF feature selection refused: the force-tolerance fraction "
510 "must be in (0, 1)";
511 return reject(std::move(report));
512 }
513 report.force_tol_fraction = fraction;
514 report.force_tolerance = fraction * kRFFForceConvergenceTolerance;
515 report.energy_tolerance =
516 fraction * sigma_e * (kRFFForceConvergenceTolerance / sigma_g);
517
518 const std::vector<int> order = rffFarthestPointOrder(observation.R);
519 if (static_cast<int>(order.size()) != n_geometries) {
520 report.detail = "RFF feature selection could not order the geometries";
521 return reject(std::move(report));
522 }
523 const std::vector<int> fit_index(order.begin(),
524 order.begin() + plan.fit_geometries);
525 const std::vector<int> hold_index(order.begin() + plan.fit_geometries,
526 order.end());
527 const Observation fit = takeRows(observation, fit_index);
528 const Observation holdout = takeRows(observation, hold_index);
529
530 // Derive validation output centering and scaling strictly from the fit
531 // split so hold-out targets never leak into the validation posteriors, and
532 // arbitrary constant energy offsets cancel in both models.
533 double fit_mean_stat = 0.0;
534 double fit_variance_stat = 0.0;
535 double fit_max_stat = 0.0;
536 residualEnergyStatistics(fit, fit_mean_stat, fit_variance_stat,
537 fit_max_stat);
538 double val_mean = std::isfinite(fit_mean_stat) ? fit_mean_stat : 0.0;
539 if (prior_mean_statistic_ == PriorMeanStatistic::Maximum &&
540 std::isfinite(fit_max_stat)) {
541 val_mean = fit_max_stat;
542 }
543 double val_scale = 1.0;
544 if (!disable_output_normalization_) {
545 const double sigma_fit =
546 (fit.E.size() > 1 && std::isfinite(fit_variance_stat) &&
547 fit_variance_stat > 0.0)
548 ? std::sqrt(fit_variance_stat)
549 : 0.0;
550 double scale_floor = 0.0;
551 if (output_scale_floor_ && fit.R.rows() > 1 &&
552 fit.G.rows() == fit.R.rows() && fit.G.cols() > 0 &&
553 jitter_sigma2 > 0.0 && std::isfinite(jitter_sigma2)) {
554 double grad_sumsq = 0.0;
555 Eigen::Index grad_rows = 0;
556 for (Eigen::Index r = 0; r < fit.G.rows(); ++r) {
557 const double sq = fit.G.row(r).squaredNorm();
558 if (!std::isfinite(sq)) continue;
559 grad_sumsq += sq;
560 ++grad_rows;
561 }
562 const Eigen::VectorXd centroid = fit.R.colwise().mean();
563 double spread_sumsq = 0.0;
564 for (Eigen::Index r = 0; r < fit.R.rows(); ++r) {
565 spread_sumsq +=
566 (fit.R.row(r).transpose() - centroid).squaredNorm();
567 }
568 const double candidate =
569 std::sqrt(jitter_sigma2) *
570 std::sqrt(
571 grad_sumsq /
572 static_cast<double>(std::max<Eigen::Index>(grad_rows, 1))) *
573 std::sqrt(spread_sumsq / static_cast<double>(fit.R.rows()));
574 if (std::isfinite(candidate) && candidate > 0.0)
575 scale_floor = candidate;
576 }
577 const double chosen_scale = std::max(sigma_fit, scale_floor);
578 if (std::isfinite(chosen_scale) && chosen_scale > 0.0)
579 val_scale = chosen_scale;
580 }
581 const double val_scale_sq = val_scale * val_scale;
582 const auto& source_kernel = getSexpAtCovarianceFunction();
583 const double physical_magn_sigma2 =
584 trainingToPhysicalNoiseVariance(source_kernel.getMagnSigma2());
585 const double physical_const_sigma2 = trainingToPhysicalNoiseVariance(
586 getConstantCovarianceFunction().getConstSigma2());
587
588 std::shared_ptr<const linalg::MpiCommunicator> shared_comm;
589#if defined(GPR_HAVE_MPI) || defined(GPR_LINALG_SCALAPACK)
590 const auto comm_ctx = mpiContext();
591 if (comm_ctx.comm != linalg::kMpiCommNull) {
592 shared_comm = std::make_shared<linalg::MpiCommunicator>(comm_ctx.comm);
593 }
594#endif
595
596 std::unique_ptr<GaussianProcessRegression> exact_holder =
597 shared_comm ? std::make_unique<GaussianProcessRegression>(shared_comm)
598 : std::make_unique<GaussianProcessRegression>();
599 GaussianProcessRegression& exact = *exact_holder;
600 try {
601 InputParameters parameters;
602 exact.initialize(parameters, atoms_config);
603 exact.setHssvdBackend(false);
604 exact.setDescriptorPredictor(false);
605 exact.setDisableOutputNormalization(disable_output_normalization_);
606 exact.y_mean_ = val_mean;
607 exact.y_scale_ = val_scale;
608 exact.y_mean_frozen_ = true;
609 exact.report_level = 0;
610 auto& kernel = exact.getSexpAtCovarianceFunction();
611 kernel = source_kernel;
612 kernel.clearDistanceCache();
613 kernel.setMagnSigma2(physical_magn_sigma2 / val_scale_sq);
614 if (kernel.getLengthScaleRef().size() !=
615 source_kernel.getLengthScaleRef().size()) {
616 report.detail =
617 "RFF feature selection could not copy the length scales";
618 return reject(std::move(report));
619 }
620 exact.getConstantCovarianceFunction().setConstSigma2(
621 physical_const_sigma2 / val_scale_sq);
622 if (ffPriorMeanActive()) exact.setUseFFPriorMean(true);
623 if (zblPriorMeanActive()) exact.setUseZBLPriorMean(true);
625 exact.setSecantQuadraticPrior(
626 secant_reference_position_, secant_reference_gradient_,
627 secant_hessian_, secant_reference_energy_);
628 if (exact.setLikelihoodNoiseVariance(energy_noise) ==
630 report.detail =
631 "RFF feature selection could not set the validation noise";
632 return reject(std::move(report));
633 }
634 exact.setJitterSigma2(0.0);
635 aux::AuxiliaryFunctionality aux_func;
636 aux_func.assembleMatrixOfRepetitiveCoordinates(fit.R, exact.R_matrix,
637 exact.R_indices);
639 exact.energy_and_gradient);
640 exact.subtractPriorMeanFromTargets(fit.R, fit.E.size(),
641 exact.energy_and_gradient);
642 exact.standardizeTargets(exact.energy_and_gradient, fit.E.size());
643 exact.full_cartesian_training_dimension_ = dimension;
644 } catch (const RFFFeatureSelectionError&) {
645 throw;
646 } catch (const std::exception& ex) {
647 report.detail =
648 std::string("exact validation posterior failed: ") + ex.what();
649 return reject(std::move(report));
650 }
651
652 const double train_energy_noise = energy_noise / val_scale_sq;
653 const double train_gradient_noise = gradient_noise / val_scale_sq;
654 if (exact.R_matrix.rows() != plan.joint_rows ||
655 exact.energy_and_gradient.size() != plan.joint_rows) {
656 report.detail =
657 "exact validation posterior did not assemble the fit design";
658 return reject(std::move(report));
659 }
660 {
661 Eigen::MatrixXd covariance;
662 exact.evaluateTrainingCovarianceMatrix(exact.R_matrix, exact.R_indices,
663 covariance, true);
664 if (covariance.rows() != plan.joint_rows ||
665 covariance.cols() != plan.joint_rows) {
666 report.detail = "exact validation Gram has the wrong order";
667 return reject(std::move(report));
668 }
669 const Eigen::Index energy_rows = fit.R.rows();
670 const Eigen::Index gradient_rows =
671 energy_rows * static_cast<Eigen::Index>(dimension);
672 covariance.diagonal().segment(energy_rows, gradient_rows).array() +=
673 (train_gradient_noise - train_energy_noise);
674 Eigen::LLT<Eigen::Ref<Eigen::MatrixXd>> factor(covariance);
675 if (factor.info() != Eigen::Success) {
676 report.detail =
677 "exact validation Gram is not positive definite under the "
678 "random-feature noise; no feature count was installed";
679 return reject(std::move(report));
680 }
681 Eigen::VectorXd alpha = factor.solve(exact.energy_and_gradient);
682 if (exact.hasTrainingPermutation())
683 exact.a = exact.permuteTrainingVector(alpha);
684 else
685 exact.a = std::move(alpha);
686 exact.is_decomposed_succesfully = true;
687 }
688
689 Observation standardized_fit = rffResidualObservation(fit);
690 if (standardized_fit.E.size() > 0) {
691 standardized_fit.E =
692 (standardized_fit.E.array() - val_mean) / val_scale;
693 }
694 if (standardized_fit.G.size() > 0 && val_scale != 1.0) {
695 standardized_fit.G /= val_scale;
696 }
697 const double standardized_energy_noise = train_energy_noise;
698 const double standardized_gradient_noise = train_gradient_noise;
699
700 std::ostringstream tried;
701 tried << "RFF feature selection";
702 bool any = false;
703 for (int features = plan.feature_start; features <= plan.feature_limit;
704 features *= 2) {
705 FeatureScore score;
706 try {
707 RFFModel model = shared_comm ? RFFModel(shared_comm) : RFFModel();
708 model.build(exact.getSexpAtCovarianceFunction(), exact.atoms_config,
709 standardized_fit, features, standardized_energy_noise,
710 standardized_gradient_noise);
711 Observation random_feature;
712 random_feature.R = holdout.R;
713 model.calculatePotential(random_feature);
714 if (val_scale != 1.0 || val_mean != 0.0) {
715 if (random_feature.E.size() > 0) {
716 random_feature.E =
717 val_scale * random_feature.E.array() + val_mean;
718 }
719 if (random_feature.G.size() > 0 && val_scale != 1.0) {
720 random_feature.G *= val_scale;
721 }
722 }
723 addPriorMeanToObservation(random_feature);
724
725 Observation reference;
726 reference.R = holdout.R;
727 exact.calculatePotentialDispatched(reference);
728
729 score.max_energy_error =
730 maxAbsEnergy(random_feature.E, reference.E, holdout.R.rows());
731 score.max_force_error = maxAbsForce(random_feature.G, reference.G);
732 score.max_energy_oracle_error =
733 maxAbsEnergy(random_feature.E, holdout.E, holdout.R.rows());
734 score.max_force_oracle_error =
735 maxAbsForce(random_feature.G, holdout.G);
736 score.exact_energy_oracle_error =
737 maxAbsEnergy(reference.E, holdout.E, holdout.R.rows());
738 score.exact_force_oracle_error =
739 maxAbsForce(reference.G, holdout.G);
740 score.finite = std::isfinite(score.max_energy_error) &&
741 std::isfinite(score.max_force_error);
742 } catch (const std::exception& ex) {
743 score.failure = ex.what();
744 }
745
746 report.max_energy_error = score.max_energy_error;
747 report.max_force_error = score.max_force_error;
748 report.max_energy_oracle_error = score.max_energy_oracle_error;
749 report.max_force_oracle_error = score.max_force_oracle_error;
750 report.exact_energy_oracle_error = score.exact_energy_oracle_error;
751 report.exact_force_oracle_error = score.exact_force_oracle_error;
752
753 if (any) tried << ";";
754 any = true;
755 tried << " D=" << features << " energy=" << sci(score.max_energy_error)
756 << " force=" << sci(score.max_force_error);
757 if (!score.failure.empty()) tried << " build_failed";
758
759 const bool meets = score.finite &&
760 score.max_energy_error <= report.energy_tolerance &&
761 score.max_force_error <= report.force_tolerance;
762 if (meets) {
763 report.accepted = true;
764 report.features = features;
765 report.status = "accepted";
766 tried << " accepted";
767 tried << " fraction=" << sci(report.force_tol_fraction)
768 << " energy_tol=" << sci(report.energy_tolerance)
769 << " force_tol=" << sci(report.force_tolerance)
770 << " fit=" << report.fit_geometries
771 << " holdout=" << report.holdout_geometries
772 << " gram_bytes=" << report.exact_gram_bytes
773 << " cap_bytes=" << report.memory_cap_bytes
774 << " oracle_rff_energy=" << sci(score.max_energy_oracle_error)
775 << " oracle_rff_force=" << sci(score.max_force_oracle_error)
776 << " oracle_exact_energy="
777 << sci(score.exact_energy_oracle_error)
778 << " oracle_exact_force="
779 << sci(score.exact_force_oracle_error);
780 report.detail = tried.str();
781 rff_selection_ = report;
782 logRFFFeatureSelection(report);
783 return report;
784 }
785 if (features > plan.feature_limit / 2) break;
786 }
787
788 tried << " rejected: held-out RFF-vs-exact error stayed above energy "
789 << sci(report.energy_tolerance) << " eV and force "
790 << sci(report.force_tolerance)
791 << " eV/A through D=" << plan.feature_limit
792 << ". No feature count was installed.";
793 report.detail = tried.str();
794 report.features = 0;
795 return reject(std::move(report));
796}
RFFValidationPlan planRFFFeatureValidation(int n_geometries, int cartesian_dimension, std::uint64_t memory_cap_bytes)
constexpr double kRFFForceConvergenceTolerance
Band force tolerance the random-feature error is not allowed to cross.
std::vector< int > rffFarthestPointOrder(const Eigen::MatrixXd &positions)

◆ serialFactorReusesForTesting()

std::size_t gpr::GaussianProcessRegression::serialFactorReusesForTesting ( ) const
inlinenodiscardnoexcept

Definition at line 2710 of file GaussianProcessRegression.h.

2711 {
2712 return serial_factor_reuses_for_testing_;
2713 }

◆ setActivePosteriorRefits()

void gpr::GaussianProcessRegression::setActivePosteriorRefits ( bool enabled)
inlinenoexcept

Definition at line 572 of file GaussianProcessRegression.h.

573 {
574 active_posterior_refits_ = enabled;
576 }

◆ setAdditivePairResiduals()

void gpr::GaussianProcessRegression::setAdditivePairResiduals ( bool enabled)
inlinenoexcept

Compare an additive two-body correction, one squared-exponential per chemical pair type on the inverse distance summed over the pairs, alone and on top of the pair correction. Environment refinements share their declared chemical parent in this component. Selected only if NLML and geometry LOO improve.

Definition at line 593 of file GaussianProcessRegression.h.

594 {
595 additive_pair_residuals_ = enabled;
596 // The correction lives in the active refit, as for SOAP.
597 if (enabled) active_posterior_refits_ = true;
598 }

◆ setAnnealStage()

void gpr::GaussianProcessRegression::setAnnealStage ( bool enabled,
std::size_t budget,
std::size_t replicas,
std::size_t every,
std::uint64_t seed )
inline

The anneal stage before the local MAP fit (AnnealStage.h): a box ensemble of replicas chains with budget work units, run on the first fit and on every every-th fit after it. enabled turns the stage on. A zero budget spends what the last local fit spent (at least one evaluation per independent, unpinned parameter plus one); a zero every runs the stage on the first full fit and then only on evidence against the surrogate (a measured force error at or above the force tolerance, or a local fit that did not converge); a positive every runs it on every such fit regardless. The box half-width is the length-scale prior's scale. A build without the anneal subproject refuses the stage instead of accepting the request and fitting without it.

Definition at line 2307 of file GaussianProcessRegression.h.

2309 {
2310#ifndef USE_ANNEAL
2311 if (enabled)
2312 throw std::invalid_argument(
2313 "the anneal stage is not compiled into this build: configure "
2314 "with -Duse_anneal=enabled (the anneal subproject needs "
2315 "rgmin)");
2316#endif
2317 anneal_enabled_ = enabled;
2318 anneal_budget_ = budget;
2319 anneal_replicas_ = replicas == 0 ? 1 : replicas;
2320 anneal_every_ = every;
2321 anneal_seed_ = seed;
2322 anneal_fit_counter_ = 0;
2323 surrogate_contradicted_ = false;
2324 }

◆ setAtomicEnvironmentModel()

void gpr::GaussianProcessRegression::setAtomicEnvironmentModel ( bool enabled)

Fit an additive atomic-environment posterior to complete physical energy and Cartesian-gradient observations. Refits optimize the full atomic parameter vector; pair-length active-refit masks do not apply.

Definition at line 233 of file AtomicEnvironment.cpp.

234{
235#ifndef GPR_USE_FEATOMIC
236 if (enabled)
237 throw std::invalid_argument(
238 "atomic environment models require featomic support");
239#endif
240 if (atomic_environment_model_ == enabled) return;
241 invalidateLikelihoodNoiseDependentState();
242 atomic_environment_model_ = enabled;
243 atomic_environment_posterior_.reset();
244 atomic_environment_parameters_.resize(0);
245 atomic_environment_parameter_species_.clear();
246 active_posterior_.reset();
247 full_fit_observations_.clear();
249 has_been_optimized_ = false;
250 ++factor_epoch_;
251}

◆ setChainImageCount()

void gpr::GaussianProcessRegression::setChainImageCount ( int n)
inline

Set the NEB chain image count so optimize() can apply image-count-adaptive length-scale controls where configured.

Definition at line 3314 of file GaussianProcessRegression.h.

3315 {
3316 chain_image_count_ = n;
3317 }

◆ setChemFactorizedHyperparameters()

void gpr::GaussianProcessRegression::setChemFactorizedHyperparameters ( bool enabled)
inlinenoexcept

Definition at line 1173 of file GaussianProcessRegression.h.

1174 {
1175 use_chem_factorized_hyper_ = enabled;
1176 }

◆ setConditionedHessian()

void gpr::GaussianProcessRegression::setConditionedHessian ( const Eigen::VectorXd & point,
const Eigen::MatrixXd & hessian )

Definition at line 168 of file GaussianProcessRegression.cpp.

170{
171 if (!optimizer_state_) return;
172 auto& entries = optimizer_state_->conditioned_hessians;
173 for (auto& entry: entries) {
174 if (entry.point.size() == point.size() &&
175 (entry.point - point).lpNorm<Eigen::Infinity>() <=
176 1e-12 * std::max(1.0, point.lpNorm<Eigen::Infinity>())) {
177 entry.point = point;
178 entry.hessian = hessian;
179 return;
180 }
181 }
182 entries.push_back({point, hessian});
183}

◆ setCutlassPluginPath()

void gpr::GaussianProcessRegression::setCutlassPluginPath ( std::string path)
inline

Definition at line 2073 of file GaussianProcessRegression.h.

2074 {
2075 cutlass_plugin_path_ = std::move(path);
2076 }

◆ setDeltaMaxRatio()

void gpr::GaussianProcessRegression::setDeltaMaxRatio ( double v)
inlinenoexcept

Definition at line 2157 of file GaussianProcessRegression.h.

2158 {
2159 delta_max_ratio_ = v;
2160 }

◆ setDeltaUHMinDiag()

void gpr::GaussianProcessRegression::setDeltaUHMinDiag ( double v)
inlinenoexcept

DELTA-method robustness knobs. The alpha-K Hessian Laplace correction delta_var(x*) = g(x*)^T H^{-1} g(x*) where H is the NLML Hessian at theta_MAP, blows up when H is ill-conditioned (small min(diag(U_H)) at small training-set size). Observed 1e15-1e17 eV^2 on Baker-NEB 01_hcn outer iters 0 to 8 vs MAP variance of order 1 eV^2; the pure LAPLACE-SLICE arm without DELTA stays bounded. Two complementary guards applied inside calculateVarianceLaplaceSliceDelta:

delta_uh_min_diag : skip the correction (delta_var = 0) when min(diag(U_H)) is below this floor. Default 1e-6. Set <= 0 to disable. delta_max_ratio : cap per-query delta_var at this multiple of max(magnSigma2, 1e-12). Default 100.0 (cap corrected std dev at ~10x signal std dev). Set <= 0 to disable.

Both default to active; bit-identical to the legacy DELTA path when both are set to 0.

Definition at line 2149 of file GaussianProcessRegression.h.

2150 {
2151 delta_uh_min_diag_ = v;
2152 }

◆ setDescriptorPredictor()

void gpr::GaussianProcessRegression::setDescriptorPredictor ( bool enabled)
inlinenoexcept

Predict the mean through the inverse-distance descriptor form of the kernel on every backend. The descriptor form is a reparametrisation of the Sexpat kernel (their predictions agree to rounding), and its per-row cost is O(n_feat * dof) against the O((1+dof)^2 * n_pairs) Cartesian joint-block assembly.

Definition at line 3002 of file GaussianProcessRegression.h.

3003 {
3004 descriptor_predictor_enabled_ = enabled;
3005 }

◆ setDisableOutputNormalization()

void gpr::GaussianProcessRegression::setDisableOutputNormalization ( bool d)
inlinenoexcept

Definition at line 1691 of file GaussianProcessRegression.h.

1692 {
1693 disable_output_normalization_ = d;
1694 }

◆ setEnvironmentResiduals()

void gpr::GaussianProcessRegression::setEnvironmentResiduals ( bool enabled)

Compare pair, SOAP and pair+SOAP corrections on the same conditional observations. SOAP is selected only if NLML and geometry LOO improve.

Definition at line 942 of file ActivePosterior.cpp.

943{
944#if !defined(GPR_USE_FEATOMIC)
945 if (enabled)
946 throw std::invalid_argument(
947 "environment residual fitting requires featomic and rgmin");
948#endif
949 if (enabled != environment_residuals_) {
950 active_posterior_.reset();
951 active_kernel_evidence_.clear();
952 ++factor_epoch_;
953 }
954 environment_residuals_ = enabled;
955 if (enabled) active_posterior_refits_ = true;
956}

◆ setFitStepStop()

void gpr::GaussianProcessRegression::setFitStepStop ( bool use)
inlinenoexcept

Whether the auto stationarity mode also ends each fit at its scale.

Definition at line 1440 of file GaussianProcessRegression.h.

1441 {
1442 fit_step_stop_ = use;
1443 scg_opt_settings.stationarity_step_stop =
1444 objective_stationarity_skip_auto_ && use;
1445 }

◆ setFitTolerancesForTesting()

void gpr::GaussianProcessRegression::setFitTolerancesForTesting ( double objective,
double step )
inlinenoexcept

The fit's objective and step tolerances (the rgmin gradient tolerance is their minimum).

Definition at line 2565 of file GaussianProcessRegression.h.

2566 {
2567 scg_opt_settings.common.tolerance_func = objective;
2568 scg_opt_settings.common.tolerance_sol = step;
2569 }

◆ setForceFactorOwnerLaplaceMeanForTesting()

void gpr::GaussianProcessRegression::setForceFactorOwnerLaplaceMeanForTesting ( bool value)
inlinenoexcept

Definition at line 2673 of file GaussianProcessRegression.h.

2674 {
2675 force_factor_owner_laplace_mean_for_testing_ = value;
2676 }

◆ setGeodesicHeatPrior()

void gpr::GaussianProcessRegression::setGeodesicHeatPrior ( std::shared_ptr< const GeodesicHeatEnergyForceKernel > kernel)

Attach a fitted heat component and select its exact execution paths. The component retains its own reference geometry and pair metric.

Definition at line 2208 of file GaussianProcessRegression.cpp.

2210{
2211 if (!sexpat_cov_func)
2212 throw std::logic_error(
2213 "geodesic heat prior requires an initialized GP");
2214 sexpat_cov_func->setGeodesicHeatKernel(std::move(kernel));
2215 if (sexpat_cov_func->usesManifoldChart() ||
2216 sexpat_cov_func->usesGeodesicHeatKernel())
2217 configureExactCompositeKernel();
2218 else
2219 restoreBaseKernelExecutionConfig();
2220}

◆ setHierarchicalPrior()

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

Activate a hierarchical-Bayes Gaussian prior on this GP's SExp kernel log-parameters: ~log(theta) ~ N(mu_log, s2_log * I)~. The packed layout of ~mu_log~ matches ~packInlaHyperparameters()~ – ~[log(magnSigma2), log(lengthScale[0]), ..., log(lengthScale[K-1])]~ plus an active trailing ~log(sigma_n^2)~ likelihood-noise coordinate when present. The next ~optimize~ call adds this prior's contribution to the SCG NLML objective; setting ~mu_log~ to the session GP's MAP turns the per-image SCG into a posterior shrinkage estimator that pulls noisy small-N per-image fits back toward the global anchor. Forward to the SExp covariance function; the constant kernel (which has no learnable hyperparameter) is unaffected.

Definition at line 2072 of file GaussianProcessRegression.cpp.

2074{
2075 if (sexpat_cov_func != nullptr) {
2076 sexpat_cov_func->setHierarchicalPrior(mu_log, s2_log);
2077 }
2078}

◆ setHssvdBackend()

void gpr::GaussianProcessRegression::setHssvdBackend ( bool enabled)
inlinenoexcept

Definition at line 1563 of file GaussianProcessRegression.h.

1564 {
1565 use_hssvd_backend_ = enabled;
1566 }

◆ setHssvdDualChopTolerance()

void gpr::GaussianProcessRegression::setHssvdDualChopTolerance ( double tol)
inlinenoexcept

Definition at line 1605 of file GaussianProcessRegression.h.

1606 {
1607 hssvd_dual_chop_tol_ = (tol > 0.0 && tol < 1.0) ? tol : 0.0;
1608 }

◆ setHssvdDualLapackRrr()

void gpr::GaussianProcessRegression::setHssvdDualLapackRrr ( bool enabled)
inlinenoexcept

Definition at line 1621 of file GaussianProcessRegression.h.

1622 {
1623 hssvd_dual_lapack_rrr_ = enabled;
1624 }

◆ setHssvdDualRandomizedSketch()

void gpr::GaussianProcessRegression::setHssvdDualRandomizedSketch ( int sketch_size)
inlinenoexcept

Definition at line 1613 of file GaussianProcessRegression.h.

1614 {
1615 hssvd_dual_randomized_sketch_ = sketch_size > 0 ? sketch_size : 0;
1616 }

◆ setHssvdHessianBlockApplyFailsForTesting()

void gpr::GaussianProcessRegression::setHssvdHessianBlockApplyFailsForTesting ( bool fail) const
noexcept

Make the dense HS-SVD block apply fail for one test.

The vector product is unchanged. The dense assembly treats the failed apply as a final refusal and does not build action columns.

Definition at line 149 of file GaussianProcessRegression.cpp.

151{
152 optimizer_state_->mean_hessian.hssvd_block_apply_fails = fail;
153}

◆ setHssvdLocalActiveSetSize()

void gpr::GaussianProcessRegression::setHssvdLocalActiveSetSize ( int size)
inlinenoexcept

Definition at line 1632 of file GaussianProcessRegression.h.

1633 {
1634 hssvd_local_active_set_size_ = size > 0 ? size : 0;
1635 }

◆ setHssvdLocalPosteriorActiveSetSize()

void gpr::GaussianProcessRegression::setHssvdLocalPosteriorActiveSetSize ( int size)
inlinenoexcept

Definition at line 1643 of file GaussianProcessRegression.h.

1644 {
1645 hssvd_local_posterior_active_set_size_ = size > 0 ? size : 0;
1646 }

◆ setHssvdObjectiveContractions()

void gpr::GaussianProcessRegression::setHssvdObjectiveContractions ( bool enabled)
inlinenoexcept

Definition at line 1597 of file GaussianProcessRegression.h.

1598 {
1599 use_hssvd_objective_contractions_ = enabled;
1600 }

◆ setHssvdRetainedSpectrumForTesting()

void gpr::GaussianProcessRegression::setHssvdRetainedSpectrumForTesting ( Eigen::MatrixXd psi,
Eigen::VectorXd singular_values )
inline

Definition at line 2879 of file GaussianProcessRegression.h.

2881 {
2882 hssvd_basis_.setRetainedSpectrumForTesting(std::move(psi),
2883 std::move(singular_values));
2884 }

◆ setHssvdVarianceCalibrationFactorForTesting()

void gpr::GaussianProcessRegression::setHssvdVarianceCalibrationFactorForTesting ( double factor)
inlinenoexcept

Definition at line 2834 of file GaussianProcessRegression.h.

2835 {
2836 hssvd_variance_calibration_factor_ = factor;
2837 }

◆ setHutchinsonProbes()

void gpr::GaussianProcessRegression::setHutchinsonProbes ( int num_probes)
inlinenoexcept

Definition at line 1552 of file GaussianProcessRegression.h.

1553 {
1554 hutch_num_probes_ = num_probes > 0 ? num_probes : 0;
1555 }

◆ setHyperparameterActiveMaskForTesting()

void gpr::GaussianProcessRegression::setHyperparameterActiveMaskForTesting ( const std::vector< bool > & mask)
inline

Definition at line 2522 of file GaussianProcessRegression.h.

2523 {
2524 scg_opt_settings.active_parameters = mask;
2525 }

◆ setHyperparameterObjectiveMode()

void gpr::GaussianProcessRegression::setHyperparameterObjectiveMode ( HyperparameterObjectiveMode mode)
inlinenoexcept

Definition at line 2384 of file GaussianProcessRegression.h.

2386 {
2387 hyperparameter_objective_mode_ = mode;
2388 }

◆ setHyperparameterOptimizationMode()

void gpr::GaussianProcessRegression::setHyperparameterOptimizationMode ( HyperparameterOptimizationMode mode)
noexcept

Explicit mode selection. It outranks the optimization_alg string of any InputParameters applied later through initialize(), so a profile default cannot silently undo a run's configured mode.

Definition at line 261 of file GaussianProcessRegression.cpp.

263{
264 hyperparameter_mode_override_ = mode;
265 selectHyperparameterOptimizer(mode);
266 ++laplace_model_revision_;
267}

◆ setHyperparameters()

void gpr::GaussianProcessRegression::setHyperparameters ( const Observation & all_obs,
const AtomsConfiguration & conf_info,
const bool update_sexpat_cf_param = true,
const bool update_const_cf_param = true,
const bool update_sqrt_prior_param = true )

Set up hyperparameters for GPR.

Parameters
all_obsStructure of all observations
conf_infoStructure of atoms configuration
update_sexpat_cf_paramSet to "true" to update parameters of the SexpAt covariance function
update_const_cf_paramSet to "true" to update parameters of the Constant covariance function
update_sqrt_prior_paramSet to "true" to update parameters of the SQRT prior

Definition at line 1405 of file GaussianProcessRegression.cpp.

1409{
1410 ScopedPhaseTimer setup_timer(PhaseTimers::setup_seconds);
1411 detail::requireJointTrainingObservation(
1412 all_obs, "GaussianProcessRegression::setHyperparameters",
1413 /*allow_empty=*/true);
1414 if (atomic_environment_model_) {
1415 updateConfiguration(conf_info);
1417 invalidateLikelihoodNoiseDependentState();
1418 return;
1419 }
1421 !update_sexpat_cf_param && !update_const_cf_param &&
1422 !update_sqrt_prior_param && canConditionActivePosterior(all_obs)) {
1423 active_refit_setup_skipped_ = true;
1424 return;
1425 }
1428 active_posterior_.reset();
1429 const bool fixed_chart =
1430 sexpat_cov_func != nullptr && sexpat_cov_func->usesManifoldChart();
1431 const bool update_sexpat = update_sexpat_cf_param && !fixed_chart;
1432 const bool update_constant = update_const_cf_param && !fixed_chart;
1433 const bool update_sqrt_prior = update_sqrt_prior_param && !fixed_chart;
1434 if (update_sexpat || update_constant || update_sqrt_prior) {
1435 invalidateObjectiveStationarityHessian();
1436 }
1437 configureZBLPriorMean(conf_info);
1438 configureFFPriorMean(conf_info);
1439
1440 PriorBase prior_parameters;
1441
1442 const bool has_energy = all_obs.E.size() > 0;
1443 const bool has_positions = all_obs.R.rows() > 0 && all_obs.R.cols() > 0;
1444 // The energy mean is the constant prior mean, needed in BOTH branches:
1445 // a zero-mean GP on raw absolute energies reverts every extrapolation
1446 // toward 0 eV absolute and inflates the signal-variance seed to
1447 // mean(y^2) ~ E_abs^2.
1448 const bool needs_output_statistics = true;
1449 const bool needs_prior_scale_update =
1450 sexpat_cov_func != nullptr && !fixed_chart;
1451
1452 // Every later use of the kernel assumes it is allocated. Reject a
1453 // missing one before the first dereference, including the classic
1454 // nu check below.
1455 if (sexpat_cov_func == nullptr) {
1456 throw std::invalid_argument(
1457 "Sexpat covariance function is not allocated");
1458 }
1459
1460#ifndef NDEBUG
1461 gpr::assertMsg(const_cov_fun != nullptr,
1462 "Object of constant covariance function is not allocated!");
1463 gpr::assertMsg(sexpat_cov_func != nullptr,
1464 "Object of sexpAt covariance function is not allocated!");
1465#endif
1466
1467 // OUTPUT standardization (transform-at-the-GP-boundary): the GP trains on
1468 // standardized targets E~=(E-mean_E)/sigma_E and the Cartesian gradient
1469 // G~=G/sigma_E (= grad_R of the standardized energy; derived in
1470 // scripts/derive_gp_normalization.py). y_mean_/y_scale_ un-normalize
1471 // predictions. The signal scale is the unbiased target variance when a
1472 // Bayesian hyperparameter bracketing path needs it.
1473 const double physical_likelihood_variance =
1474 lik_gaussian != nullptr
1475 ? trainingToPhysicalNoiseVariance(lik_gaussian->getSigma2())
1476 : 0.0;
1477 const double physical_signal_variance =
1478 trainingToPhysicalNoiseVariance(sexpat_cov_func->getMagnSigma2());
1479 const double physical_constant_variance =
1480 trainingToPhysicalNoiseVariance(const_cov_fun->getConstSigma2());
1481 const double previous_output_scale = y_scale_;
1482 double mean_y = 0.0;
1483 double target_variance = 0.0;
1484 double sigma_E = 0.0;
1485 if (needs_output_statistics && has_energy) {
1486 double max_y = 0.0;
1487 residualEnergyStatistics(all_obs, mean_y, target_variance, max_y);
1488 if (prior_mean_statistic_ == PriorMeanStatistic::Maximum &&
1489 std::isfinite(max_y))
1490 mean_y = max_y;
1491 }
1492 if (needs_output_statistics && has_energy && all_obs.E.size() > 1) {
1493 if (std::isfinite(target_variance) && target_variance > 0.0)
1494 sigma_E = std::sqrt(target_variance);
1495 }
1496 // The floor depends on the training rows only: the energy scale the
1497 // gradient data imply bounds the amplification of the standardized
1498 // gradient targets. It is covariant under an energy rescaling E -> cE
1499 // (the gradient scale and sigma_E both scale by c) and invariant under a
1500 // geometry rescaling R -> aR (|G| scales by 1/a, the spread by a).
1501 double scale_floor = 0.0;
1502 if (output_scale_floor_ && has_energy && all_obs.R.rows() > 1 &&
1503 all_obs.G.rows() == all_obs.R.rows() && all_obs.G.cols() > 0 &&
1504 jitter_sigma2 > 0.0 && std::isfinite(jitter_sigma2)) {
1505 double gradient_sumsq = 0.0;
1506 Eigen::Index gradient_rows = 0;
1507 for (Eigen::Index row = 0; row < all_obs.G.rows(); ++row) {
1508 const double squared = all_obs.G.row(row).squaredNorm();
1509 if (!std::isfinite(squared)) continue;
1510 gradient_sumsq += squared;
1511 ++gradient_rows;
1512 }
1513 const Eigen::VectorXd centroid = all_obs.R.colwise().mean();
1514 double spread_sumsq = 0.0;
1515 for (Eigen::Index row = 0; row < all_obs.R.rows(); ++row)
1516 spread_sumsq +=
1517 (all_obs.R.row(row).transpose() - centroid).squaredNorm();
1518 const double candidate =
1519 std::sqrt(jitter_sigma2) *
1520 std::sqrt(
1521 gradient_sumsq /
1522 static_cast<double>(std::max<Eigen::Index>(gradient_rows, 1))) *
1523 std::sqrt(spread_sumsq / static_cast<double>(all_obs.R.rows()));
1524 if (std::isfinite(candidate) && candidate > 0.0)
1525 scale_floor = candidate;
1526 }
1527 const bool have_scale =
1528 (std::isfinite(sigma_E) && sigma_E > 0.0) || scale_floor > 0.0;
1529 // Config-gated: the HS-SVD stable basis solves at cond=1 regardless of
1530 // target scale, so output standardization is optional there. Leaving raw
1531 // targets (y_scale_=1, y_mean_=0) exposes whether the prediction
1532 // cancellation actually harms the forces on the HS-SVD path.
1533 if (disable_output_normalization_) {
1534 // The flag disables SCALE standardization only (the HS-SVD stable
1535 // basis solves at cond=1 regardless of target scale). Mean
1536 // centering is a different object: the constant prior mean. The
1537 // constant-offset kernel is zeroed below under the assumption the
1538 // targets are centered, so the mean must be centered here too.
1539 //
1540 // FROZEN after the first data-bearing fit: any constant m is a
1541 // valid prior mean (posterior mean = m + k^T alpha); what matters
1542 // is that every row in the model is centered by the SAME m. The
1543 // HS-SVD basis appends rows incrementally between full rebuilds,
1544 // so a per-refit drifting mean labels same-region rows with
1545 // different targets -- an O(eV) drift against a 1e-2 eV noise
1546 // scale is a thousand-sigma self-contradiction the optimizer can
1547 // only explain by inflating the signal variance.
1548 if (!y_mean_frozen_ && has_energy) {
1549 y_mean_ = mean_y;
1550 y_mean_frozen_ = true;
1551 }
1552 y_scale_ = 1.0;
1553 } else {
1554 y_mean_ = mean_y;
1555 y_scale_ = have_scale ? std::max(sigma_E, scale_floor) : 1.0;
1556 }
1557
1558 if (lik_gaussian != nullptr &&
1559 std::isfinite(physical_likelihood_variance) &&
1560 physical_likelihood_variance >= 0.0) {
1561 const double training_variance =
1562 physicalToTrainingNoiseVariance(physical_likelihood_variance);
1563 if (training_variance != lik_gaussian->getSigma2()) {
1564 // Likelihood variance follows the same output transformation as
1565 // energies and Cartesian gradients, preserving its physical units.
1566 lik_gaussian->setSigma2(training_variance);
1567 invalidateLikelihoodNoiseDependentState();
1568 }
1569 }
1570
1571 const double output_scale_ratio = previous_output_scale / y_scale_;
1572 sexpat_cov_func->rescaleGeodesicHeatCovariance(output_scale_ratio *
1573 output_scale_ratio);
1574
1575 // A warm kernel retains its covariance in physical output units.
1576 // Signal and constant variances follow the same transform as noise.
1577 if (!(update_sexpat && update_constant)) {
1578 sexpat_cov_func->setMagnSigma2(
1579 physicalToTrainingNoiseVariance(physical_signal_variance));
1580 }
1581 if (!update_constant) {
1582 const_cov_fun->setConstSigma2(
1583 physicalToTrainingNoiseVariance(physical_constant_variance));
1584 }
1585
1586 if (update_constant) {
1587 // Energy is mean-centred by the y_mean_ transform, so the GP models a
1588 // zero-mean residual; the constant-offset kernel contributes nothing.
1589 const_cov_fun->setConstSigma2(0.0);
1590 }
1591
1592 if (update_sexpat) {
1593 if (update_constant) {
1594 // Standardized output -> unit signal variance.
1595 sexpat_cov_func->setMagnSigma2(1.0);
1596 }
1597 sexpat_cov_func->getLengthScaleRef().resize(1, conf_info.n_pt);
1598
1599 // INPUT standardization in the kernel's OWN inverse-distance feature
1600 // space (BoTorch/GPyTorch standard: scale inputs so the SE
1601 // length-scale prior is correct). Per pairtype l_k = std of descriptor
1602 // dimension k over the training set. This is the dimensionally correct
1603 // length scale (a Cartesian scale like sigma_E/sigma_G is the wrong
1604 // units for a descriptor-space kernel). The descriptor spread depends
1605 // on the sampled geometries, NOT the NEB image count, so l_k is
1606 // image-count-free and carries no Cartesian range divisor.
1607 // rho0_k anchor (per-pairtype descriptor std): shared with
1608 // performHyperparameterOptimization's scale-free MAP lengthscale
1609 // prior via computePairtypeDescriptorScale (see MapObjective.h).
1610 Eigen::VectorXd ls_k;
1611 bool have_descriptor_scale =
1612 computePairtypeDescriptorScale(all_obs.R, conf_info, ls_k);
1613 if (have_descriptor_scale) poolDescriptorScaleByTies(ls_k);
1614 // Data-derived width of the two-sided length-scale prior
1615 // (use_ls_prior_): the mean squared coefficient of variation of the
1616 // descriptors, i.e. the data's own relative log-scale spread. No magic
1617 // number.
1618 double ls_prior_s2_log = 0.0;
1619 if (has_positions && all_obs.R.rows() > 0) {
1620 Eigen::VectorXd phi;
1621 std::vector<Eigen::VectorXd> phi_rows;
1622 phi_rows.reserve(static_cast<size_t>(all_obs.R.rows()));
1623 for (Eigen::Index r = 0; r < all_obs.R.rows(); ++r) {
1624 Coord xr = all_obs.R.row(r);
1625 InverseDistanceDescriptor::compute(xr, conf_info, phi);
1626 phi_rows.push_back(phi);
1627 }
1628 // Prior width = var(log pairwise descriptor distance): the actual
1629 // spread of length scales present in the band, NOT the per-pairtype
1630 // descriptor-value CV^2. CV^2 collapses for a rigid simple system
1631 // (01 HCN) -> pins l -> flat posterior variance -> the acquisition
1632 // admits near-duplicates to the wall cap. Pairwise distances stay
1633 // informative even when each descriptor value barely varies. Data-
1634 // derived, no magic number.
1635 double dlog_sum = 0.0, dlog_sq = 0.0;
1636 long npair = 0;
1637 for (size_t a = 0; a < phi_rows.size(); ++a)
1638 for (size_t b = a + 1; b < phi_rows.size(); ++b) {
1639 const double d = (phi_rows[a] - phi_rows[b]).norm();
1640 if (d > 0.0 && std::isfinite(d)) {
1641 const double ld = numerics::log(d);
1642 dlog_sum += ld;
1643 dlog_sq += ld * ld;
1644 ++npair;
1645 }
1646 }
1647 if (npair > 1) {
1648 const double m = dlog_sum / static_cast<double>(npair);
1649 const double v = dlog_sq / static_cast<double>(npair) - m * m;
1650 if (std::isfinite(v) && v > 0.0) ls_prior_s2_log = v;
1651 }
1652 }
1653
1654 // Each pair type keeps its measured descriptor motion. Types with
1655 // no sampled motion use the inverse covalent bond length because
1656 // the kernel acts on 1/r, in inverse Angstrom.
1657 const priors::CovalentBondPrior bond_prior(conf_info);
1658 const Eigen::VectorXd chemical_scales =
1659 bond_prior.lengthScalePerPairtype().cwiseInverse();
1660 if (ls_k.size() != conf_info.n_pt) ls_k = chemical_scales;
1661 for (Index_t k = 0; k < conf_info.n_pt; ++k) {
1662 if (!std::isfinite(ls_k(k)) || ls_k(k) <= 0.0)
1663 ls_k(k) = chemical_scales(k);
1664 else if (ls_seed_chemical_floor_ &&
1665 std::isfinite(chemical_scales(k)) &&
1666 chemical_scales(k) > 0.0)
1667 ls_k(k) = std::max(ls_k(k), chemical_scales(k));
1668 sexpat_cov_func->getLengthScaleRef()(0, k) = ls_k(k);
1669 }
1670 if (conf_info.n_pt > 0) {
1671 // One scale per fitted parameter: each tie group counts once.
1672 const auto& ties = length_scale_ties_;
1673 if (ties.valid && ties.count() == conf_info.n_pt) {
1674 double sum = 0.0;
1675 int groups = 0;
1676 for (Index_t k = 0; k < conf_info.n_pt; ++k) {
1677 if (ties.leader[k] != k) continue;
1678 sum += ls_k(k);
1679 ++groups;
1680 }
1681 seed_length_scale_ = sum / static_cast<double>(groups);
1682 } else {
1683 seed_length_scale_ = ls_k.mean();
1684 }
1685 }
1686
1687 // use_ls_prior_: TWO-SIDED log-Gaussian length-scale prior centred on
1688 // the chemistry scale rho0_k (per-pairtype descriptor std) with width
1689 // ls_prior_s2_log = var(log pairwise descriptor distance), computed
1690 // above. It penalises BOTH collapse (l<<rho0 -> posterior variance
1691 // pins at prior, system 20) and over-smoothing (l>>rho0 -> mislocated
1692 // saddle/drift, system 10), with NO magic tail probability. Reuses
1693 // the hierarchical-Gaussian prior (log(theta) ~ N(mu_log, s2_log I));
1694 // mu_log[0]=log(magnSigma2) anchors the amplitude at the robust
1695 // energy spread. The log-distance width stays informative even on a
1696 // rigid simple system whose per-descriptor CV collapses (01 HCN),
1697 // because pairwise row distances span the fine-step-to-full-path
1698 // ratio structure. Opt-in via use_ls_prior_ (--ls-prior).
1699 const bool use_ls_prior =
1700 use_ls_prior_ && conf_info.n_pt > 0 && have_descriptor_scale &&
1701 ls_prior_s2_log > 0.0 && std::isfinite(ls_prior_s2_log);
1702 if (use_ls_prior) {
1703 Eigen::VectorXd mu_log(conf_info.n_pt + 1);
1704 // Anchor the magnSigma2 (signal-variance) prior MEAN to the data's
1705 // energy spread -- a STABLE scale -- not the drifting current
1706 // magnSigma2. Re-centering the prior on getMagnSigma2() each refit
1707 // imposes no constraint on the amplitude: SCG ratchets magnSigma2
1708 // up on a rough PES and the posterior variance (proportional to
1709 // magnSigma2) blows up unboundedly (system 20: max posterior var ->
1710 // 1e5, the band steps into extrapolation and never relaxes so the
1711 // CI never activates). var(observed energies) is the textbook GP
1712 // signal- variance scale and is data-derived (no magic number); the
1713 // prior now pulls the amplitude back toward the data scale instead
1714 // of chasing it. Falls back to the current magnSigma2 only if the
1715 // energy spread is unavailable/degenerate. ROBUST energy signal
1716 // variance (sigma = 1.4826 * MAD), matching the SCG magnSigma2
1717 // ceiling: a plain Var(E) is inflated by the transient clash
1718 // geometries the band samples during active learning, which would
1719 // push the magnSigma2 prior mean up and let the posterior variance
1720 // blow up. The MAD tracks the barrier-scale spread of the reaction
1721 // path and ignores the clash tail. No tunable.
1722 std::vector<double> evals;
1723 evals.reserve(static_cast<std::size_t>(all_obs.E.size()));
1724 for (Eigen::Index r = 0; r < all_obs.E.rows(); ++r)
1725 for (Eigen::Index c = 0; c < all_obs.E.cols(); ++c) {
1726 const double ev = all_obs.E(r, c);
1727 if (std::isfinite(ev)) evals.push_back(ev);
1728 }
1729 const long e_n = static_cast<long>(evals.size());
1730 double signal_var = 0.0;
1731 if (e_n > 1) {
1732 std::vector<double> s = evals;
1733 std::sort(s.begin(), s.end());
1734 const auto med = [](std::vector<double>& v) {
1735 const std::size_t m = v.size();
1736 return (m % 2) ? v[m / 2] : 0.5 * (v[m / 2 - 1] + v[m / 2]);
1737 };
1738 const double e_median = med(s);
1739 std::vector<double> ad(evals.size());
1740 for (std::size_t i = 0; i < evals.size(); ++i)
1741 ad[i] = std::abs(evals[i] - e_median);
1742 std::sort(ad.begin(), ad.end());
1743 const double mad = med(ad);
1744 const double robust_var = (1.4826 * mad) * (1.4826 * mad);
1745 // When more than half the energies tie, as the two
1746 // symmetry-equivalent endpoints of a three-row band do, the
1747 // MAD is their round-off. A robust spread inside the
1748 // likelihood noise does not resolve the signal, so the plain
1749 // variance anchors it.
1750 const double noise_variance =
1751 std::isfinite(physical_likelihood_variance)
1752 ? std::max(physical_likelihood_variance, 0.0)
1753 : 0.0;
1754 if (std::isfinite(robust_var) && robust_var > noise_variance) {
1755 signal_var = robust_var;
1756 } else {
1757 double e_mean = 0.0;
1758 for (double v: evals)
1759 e_mean += v;
1760 e_mean /= static_cast<double>(e_n);
1761 for (double v: evals)
1762 signal_var += (v - e_mean) * (v - e_mean);
1763 signal_var /= static_cast<double>(e_n);
1764 }
1765 }
1766 const double ms2 = sexpat_cov_func->getMagnSigma2();
1767 mu_log(0) =
1768 (std::isfinite(signal_var) && signal_var > 0.0)
1769 ? numerics::log(signal_var)
1770 : ((std::isfinite(ms2) && ms2 > 0.0) ? numerics::log(ms2)
1771 : 0.0);
1772 // Anchor the length-scale prior MEAN to the STABLE per-pairtype
1773 // descriptor std ls_k(k) (the data's own natural length scale,
1774 // computed above as the seed), NOT the drifting current length
1775 // scale. Re-centering mu_log on getLengthScaleRef() each refit
1776 // imposed no constraint: SCG ratchets l upward on the sparse early
1777 // band, the surface over-smooths, the posterior variance collapses
1778 // to ~1e-4 (confidently wrong) and the band wanders to a spurious
1779 // high saddle (hard Baker cells 04/09/16/20). ls_k is the length-
1780 // scale analogue of the var(energies) magnSigma2 anchor above:
1781 // data-derived, no magic number, measured from the actual band
1782 // (including strained/partial saddle bonds).
1783 for (Index_t k = 0; k < conf_info.n_pt; ++k) {
1784 const double lk = ls_k(k);
1785 mu_log(k + 1) =
1786 (std::isfinite(lk) && lk > 0.0) ? numerics::log(lk) : 0.0;
1787 }
1788 sexpat_cov_func->clearPcLengthScalePrior();
1789 sexpat_cov_func->setHierarchicalPrior(mu_log, ls_prior_s2_log);
1790 } else {
1791 sexpat_cov_func->clearHierarchicalPrior();
1792 sexpat_cov_func->clearPcLengthScalePrior();
1793 }
1794 // The population prior (the campaign's fits of the same element
1795 // pair) anchors the pair types it has seen at its location with
1796 // its width, the hierarchy's second level, whether or not the
1797 // run's own hierarchical prior is in force: the anchored types
1798 // carry a log-Gaussian in every prior branch of the kernel
1799 // (setHierarchicalAnchorMask), the others keep what they had.
1800 applyPopulationPrior(conf_info, ls_k,
1801 use_ls_prior ? ls_prior_s2_log : 0.0);
1802 }
1803
1804 // nu is the configured degrees of freedom of the classic Student-t
1805 // prior, not a data-seeded hyperparameter. The magnitude density
1806 // divides by it whenever that prior is active, including when this
1807 // call does not rescale s2. Only a classic profile evaluates that
1808 // density, so a non-positive nu is rejected there rather than
1809 // replaced. An extended model, and a classic model on the log-normal
1810 // magnitude prior, keeps its unused prior untouched. The covariance
1811 // function was rejected above when missing, before this dereference.
1812 if (usesClassicJointEnergyForcePrior(model_profile_) &&
1813 !sexpat_cov_func->useLogNormalMagnPrior()) {
1815 "Student-t prior", "nu",
1816 sexpat_cov_func->getPriorParametersSqrtt().getNu());
1817 }
1818
1819 if (update_sqrt_prior && std::isfinite(target_variance) &&
1820 target_variance > 0.0) {
1821 prior_parameters = sexpat_cov_func->getPriorParametersSqrtt();
1822 prior_parameters.setS2(target_variance);
1823 sexpat_cov_func->setPriorParametersSqrtt(prior_parameters);
1824 }
1825
1826 if (needs_prior_scale_update && std::isfinite(seed_length_scale_) &&
1827 seed_length_scale_ > 0.0) {
1828 prior_parameters = sexpat_cov_func->getPriorParametersGaussian();
1829 prior_parameters.setS2(seed_length_scale_ * seed_length_scale_);
1830 sexpat_cov_func->setPriorParametersGaussian(prior_parameters);
1831 }
1832
1833 ++laplace_model_revision_;
1834 laplace_posterior_.reset();
1835}
void updateConfiguration(const AtomsConfiguration &conf_info)
Update the internal atoms configuration. Use this when the set of active/frozen atoms changes dynamic...
void applyPopulationPrior(const AtomsConfiguration &conf_info, const Eigen::VectorXd &ls_k, double own_s2_log)
static void compute(const Coord &x, const AtomsConfiguration &conf_info, Eigen::VectorXd &phi)
Compute phi(x) for a single configuration.
static double setup_seconds

◆ setInternalCoordinateChart()

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

Configure this regression as a fixed-chart local molecular GP. The ordinary dense joint energy-gradient posterior remains active, while feature paths specialized to inverse-distance Sexpat geometry are disabled. Local chart models inherit or set their scalar kernel parameters and condition without a separate hyperparameter optimizer.

Definition at line 2139 of file GaussianProcessRegression.cpp.

2142{
2143 if (!sexpat_cov_func) {
2144 throw std::logic_error(
2145 "internal coordinate chart requires an initialized GP");
2146 }
2147 sexpat_cov_func->setManifoldChart(std::move(chart), length_scale);
2148 configureExactCompositeKernel();
2149}

◆ setJitterSigma2()

void gpr::GaussianProcessRegression::setJitterSigma2 ( double value)
inline

Set sigma2 jitter value.

Definition at line 2981 of file GaussianProcessRegression.inl.

2982{
2983 jitter_sigma2 = value;
2984 ++laplace_model_revision_;
2985}

◆ setKappaMax()

void gpr::GaussianProcessRegression::setKappaMax ( double kappa_max)
inlinenoexcept

Definition at line 1955 of file GaussianProcessRegression.h.

1956 {
1957 kappa_max_ = kappa_max;
1958 }

◆ setLaplaceSkipScgThreshold()

void gpr::GaussianProcessRegression::setLaplaceSkipScgThreshold ( double threshold)
inlinenoexcept

Definition at line 1415 of file GaussianProcessRegression.h.

1416 {
1417 laplace_skip_scg_threshold_ = threshold;
1418 }

◆ setLengthscaleFloor()

void gpr::GaussianProcessRegression::setLengthscaleFloor ( double floor)
inline

Absolute kernel length-scale floor for the MAP projection domain. Callers set it to the finest PES structure their sampling stencil resolves (the dimer sets its finite-difference stencil diameter); 0 disables the floor.

Definition at line 3323 of file GaussianProcessRegression.h.

3324 {
3325 lengthscale_floor_ = floor;
3326 }

◆ setLengthScaleSeedChemicalFloor()

void gpr::GaussianProcessRegression::setLengthScaleSeedChemicalFloor ( bool enabled)
inlinenoexcept

Floor each pair type's length-scale seed (and the MAP prior anchor rho0) at the covalent-bond descriptor scale 1/r_bond. The measured seed is the pair type's inverse-distance spread over the rows; a spectator pair that barely moves in the first rows gets a spread of 0.003 A^-1 where the fitted value is 0.1-0.3 (a static pair already falls back to the chemical scale, so the floor removes a cliff between "static" and "barely moving").

Definition at line 1802 of file GaussianProcessRegression.h.

1803 {
1804 ls_seed_chemical_floor_ = enabled;
1805 }

◆ setLengthScaleTies()

void gpr::GaussianProcessRegression::setLengthScaleTies ( bool enabled)

Definition at line 685 of file GaussianProcessRegression.cpp.

686{
687 if (enabled == use_length_scale_ties_) return;
688 auto state = lengthScaleFitState();
689 state.enabled = enabled;
691}
void restoreLengthScaleFitState(const LengthScaleFitState &state)

◆ setLikelihoodNoiseVariance() [1/2]

LikelihoodNoiseVarianceUpdate gpr::GaussianProcessRegression::setLikelihoodNoiseVariance ( double physical_sigma2,
const Observation & full_observation )
inlinenodiscard

Definition at line 1073 of file GaussianProcessRegression.h.

1075 {
1076 return setLikelihoodNoiseVariance(physical_sigma2, &full_observation);
1077 }

◆ setLikelihoodNoiseVariance() [2/2]

GaussianProcessRegression::LikelihoodNoiseVarianceUpdate gpr::GaussianProcessRegression::setLikelihoodNoiseVariance ( double physical_sigma2,
const Observation * full_observation = nullptr )
nodiscard

Set the likelihood noise variance in physical output units.

LikGaussian stores the converted variance in standardized training-target units. A changed value invalidates noise-dependent model state. When full_observation is non-null, that state is rebuilt from the supplied observations before this function returns.

Parameters
physical_sigma2Positive finite variance in physical output units.
full_observationOptional full training observation for rebuilding noise-dependent model state.
Returns
Invalid for a rejected value, Unchanged when both representations already match, Updated after invalidation without observations, or Rebuilt after an observation-backed rebuild.

Definition at line 310 of file GaussianProcessRegression.cpp.

312{
313 if (!std::isfinite(physical_sigma2) || !(physical_sigma2 > 0.0) ||
314 lik_gaussian == nullptr) {
316 }
317
318 const double training_sigma2 =
319 physicalToTrainingNoiseVariance(physical_sigma2);
320 if (!std::isfinite(training_sigma2) || !(training_sigma2 > 0.0)) {
322 }
323
324 const double current_training_sigma2 = lik_gaussian->getSigma2();
325 const bool representations_match =
326 std::isfinite(sigma2) && sigma2 == physical_sigma2 &&
327 std::isfinite(current_training_sigma2) &&
328 current_training_sigma2 == training_sigma2;
329 if (representations_match) {
331 }
332
333 const bool rebuild_layered_rff =
334 rff_features_ > 0 && !rff_replaces_exact_ && rff_model_.isBuilt();
335 lik_gaussian->setSigma2(training_sigma2);
336 sigma2 = physical_sigma2;
337 if (atomic_environment_model_ && atomic_environment_parameters_.size() >= 2)
338 atomic_environment_parameters_.tail(2).setConstant(
339 std::log(physical_sigma2));
340 invalidateLikelihoodNoiseDependentState();
341
342 if (full_observation == nullptr) {
344 }
345
346 updateModelWithFullData(*full_observation);
347 // buildRFFModel fits the residual of every prior mean, so no prior keeps
348 // the layered features from being rebuilt on the new noise.
349 if (rebuild_layered_rff && !rff_replaces_exact_ &&
350 is_decomposed_succesfully && rff_features_requested_ > 0 &&
351 full_observation->E.size() > 0) {
352 buildRFFModel(*full_observation, rff_features_requested_);
353 }
355}

◆ setLogRankBlockCholesky()

void gpr::GaussianProcessRegression::setLogRankBlockCholesky ( bool enabled)
inlinenoexcept

Definition at line 2039 of file GaussianProcessRegression.h.

2040 {
2041 log_rank_block_cholesky_ = false;
2042 if (enabled) {
2043 std::fprintf(stderr,
2044 "warning: logRankBlockCholesky is deprecated and "
2045 "ignored; rank-block Cholesky logging was removed\n");
2046 }
2047 }

◆ setLogTrainingGeometry()

void gpr::GaussianProcessRegression::setLogTrainingGeometry ( bool enabled)
inlinenoexcept

Definition at line 2030 of file GaussianProcessRegression.h.

2031 {
2032 log_training_geometry_ = enabled;
2033 }

◆ setMapMeanKernelForTesting()

void gpr::GaussianProcessRegression::setMapMeanKernelForTesting ( std::shared_ptr< const KernelOperator > kernel)

Install the kernel used as the MAP mean expansion.

Tests supply an exact operator the fitted covariance cannot express. A null pointer restores the Sexpat expansion.

Definition at line 123 of file GaussianProcessRegression.cpp.

125{
126 optimizer_state_->mean_hessian.map_kernel = std::move(kernel);
127}

◆ setMapMeanKernelOverridesHssvdForTesting()

void gpr::GaussianProcessRegression::setMapMeanKernelOverridesHssvdForTesting ( bool override)
noexcept

Make an installed MAP test kernel take precedence over HS-SVD.

Definition at line 129 of file GaussianProcessRegression.cpp.

131{
132 optimizer_state_->mean_hessian.map_kernel_overrides_hssvd = override;
133}

◆ setModelProfile()

void gpr::GaussianProcessRegression::setModelProfile ( GPModelProfile profile)

Select a coherent GP model family.

CHEMGP / GPRD_ZBL restore classic joint energy-force configurations as indivisible bundles (dense NLML, raw targets, classic Sexpat prior). GPRD_ZBL matches the published gpridge dimer path vendored in gprd_zbl; EXTENDED leaves independent knobs alone.

Definition at line 1292 of file GaussianProcessRegression.cpp.

1293{
1294 if (usesClassicJointEnergyForcePrior(profile) && initialized_ &&
1295 sexpat_cov_func && !sexpat_cov_func->useLogNormalMagnPrior()) {
1297 "prior", "nu", sexpat_cov_func->getPriorParametersSqrtt().getNu());
1298 }
1299 if (atomic_environment_model_ && model_profile_ != profile)
1300 invalidateLikelihoodNoiseDependentState();
1301 model_profile_ = profile;
1302 scg_opt_settings.model_profile = profile;
1303
1304 if (sexpat_cov_func) {
1305 sexpat_cov_func->setModelProfile(profile);
1306 }
1307
1308 if (!usesClassicJointEnergyForcePrior(profile)) {
1309 // EXTENDED: leave solver, objective, normalization, and prior
1310 // knobs under their existing independent controls.
1311 return;
1312 }
1313
1314 // Classic joint [E, F] profiles (CHEMGP, GPRD_ZBL): published Sexpat prior
1315 // density on raw targets with NLML/SCG. Clear experimental local/
1316 // RFF/PC overlays. A live InternalCoordinateChart stays attached so the
1317 // global tensor can be ManifoldEnergyForceKernel. Keep HS-SVD dual factor
1318 // if the caller enabled it.
1319 // Caller retains principled-nugget / ls-prior: forcing both off left the
1320 // classic posterior overconfident (Baker05 chain_var~1e-7 while true force
1321 // rose 1.3->2.1 under rejected recovery). 01-03 force_pass used NLML;
1322 // nugget defaults on in main_neb and is needed on larger Baker cells.
1330 if (sexpat_cov_func && (sexpat_cov_func->usesManifoldChart() ||
1331 sexpat_cov_func->usesGeodesicHeatKernel()))
1332 configureExactCompositeKernel();
1333 // Refits use the objective stationarity test (Newton decrement under
1334 // SCG's solution tolerance), and fits stop at that same step scale.
1335 setFitStepStop(true);
1337
1338 // Residual ZBL prior mean stays an independent CLI/config flag: the
1339 // frozen gprd_zbl input.dat defaults leave it off; enabling it is a
1340 // deliberate residual-mean choice on top of the classic kernel.
1341 ++laplace_model_revision_;
1342 laplace_posterior_.reset();
1343}
void setObjectiveStationaritySkipAuto(bool use) noexcept
void setFitStepStop(bool use) noexcept
Whether the auto stationarity mode also ends each fit at its scale.
void setHssvdLocalPosteriorActiveSetSize(int size) noexcept
void setDisableOutputNormalization(bool d) noexcept
void setHssvdLocalActiveSetSize(int size) noexcept

◆ setNlmlHessianVectorFailureForTesting()

void gpr::GaussianProcessRegression::setNlmlHessianVectorFailureForTesting ( bool fail)
inlinenoexcept

Makes evaluateNlmlHessianVector fail while exactNlmlHessianVectorAvailable() stays true.

Definition at line 2555 of file GaussianProcessRegression.h.

2556 {
2557 fail_nlml_hessian_vector_for_testing_ = fail;
2558 }

◆ setObjectiveBackend()

void gpr::GaussianProcessRegression::setObjectiveBackend ( ObjectiveBackend backend,
Eigen::Index rank = 0 )
inline

Select the objective backend. Dense is the default; Auto and Krylov opt into approximate objectives on a dense training covariance. Krylov pivots its preconditioner to rank.

Definition at line 2578 of file GaussianProcessRegression.h.

2579 {
2580 if (rank < 0)
2581 throw std::invalid_argument("Krylov rank must be nonnegative");
2583 krylov_objective_.forced_rank = rank;
2584 krylov_objective_.plan = {};
2585 krylov_objective_.solver.reset();
2586 krylov_objective_.covariance.reset();
2587 last_objective_theta_.resize(0);
2588 }

◆ setObjectiveBackendForTesting()

void gpr::GaussianProcessRegression::setObjectiveBackendForTesting ( ObjectiveBackend backend,
Eigen::Index rank = 0 )
inline

Definition at line 2589 of file GaussianProcessRegression.h.

2591 {
2593 }
void setObjectiveBackend(ObjectiveBackend backend, Eigen::Index rank=0)

◆ setObjectiveStationarityBbInverseScaleForTesting()

void gpr::GaussianProcessRegression::setObjectiveStationarityBbInverseScaleForTesting ( Eigen::Index dimension,
double inverse_scale )
inline

Definition at line 1494 of file GaussianProcessRegression.h.

1496 {
1497 objective_stationarity_bb_dimension_ = dimension;
1498 objective_stationarity_bb_inverse_scale_ = inverse_scale;
1499 objective_stationarity_bb_valid_ = dimension > 0 &&
1500 inverse_scale > 0.0 &&
1501 std::isfinite(inverse_scale);
1502 }

◆ setObjectiveStationarityHessianCholForTesting()

void gpr::GaussianProcessRegression::setObjectiveStationarityHessianCholForTesting ( const Eigen::MatrixXd & U)
inline

Definition at line 1476 of file GaussianProcessRegression.h.

1477 {
1478 objective_stationarity_hessian_chol_U_ = U;
1479 objective_stationarity_hessian_valid_ =
1480 U.rows() > 0 && U.rows() == U.cols();
1481 objective_stationarity_inverse_hessian_.resize(0, 0);
1482 objective_stationarity_inverse_hessian_valid_ = false;
1483 }

◆ setObjectiveStationarityInverseHessianForTesting()

void gpr::GaussianProcessRegression::setObjectiveStationarityInverseHessianForTesting ( const Eigen::MatrixXd & H_inverse)
inline

Definition at line 1484 of file GaussianProcessRegression.h.

1486 {
1487 objective_stationarity_hessian_chol_U_.resize(0, 0);
1488 objective_stationarity_hessian_valid_ = false;
1489 objective_stationarity_inverse_hessian_ = H_inverse;
1490 objective_stationarity_inverse_hessian_valid_ =
1491 H_inverse.rows() > 0 && H_inverse.rows() == H_inverse.cols() &&
1492 H_inverse.allFinite();
1493 }

◆ setObjectiveStationaritySkipAuto()

void gpr::GaussianProcessRegression::setObjectiveStationaritySkipAuto ( bool use)
inlinenoexcept

Definition at line 1432 of file GaussianProcessRegression.h.

1433 {
1434 objective_stationarity_skip_auto_ = use;
1435 // A refit diagnostic changes fit termination only when the caller
1436 // also selects the stationarity stopping rule.
1437 scg_opt_settings.stationarity_step_stop = use && fit_step_stop_;
1438 }

◆ setObjectiveStationaritySkipThreshold()

void gpr::GaussianProcessRegression::setObjectiveStationaritySkipThreshold ( double threshold)
inlinenoexcept

Definition at line 1424 of file GaussianProcessRegression.h.

1425 {
1426 laplace_skip_scg_threshold_ = threshold;
1427 }

◆ setOptimizationRequiredRows()

void gpr::GaussianProcessRegression::setOptimizationRequiredRows ( Coord positions)
inline

Keep these measured configurations in the hyperparameter subset. Matching rows take precedence over the history pool and FPS choices. A subset grows only when its required rows exceed the history size.

Definition at line 557 of file GaussianProcessRegression.h.

558 {
559 optimization_required_positions_ = std::move(positions);
560 }

◆ setOptimizationRowPool()

void gpr::GaussianProcessRegression::setOptimizationRowPool ( std::vector< bool > pool)
inline

Restrict the hyperparameter-optimization subset to the flagged rows of the next optimize() call; the posterior is still conditioned on every row. An empty pool or a size mismatch selects from all rows.

Definition at line 541 of file GaussianProcessRegression.h.

542 {
543 optimization_row_pool_ = std::move(pool);
544 }

◆ setOptimizationSubsetHistory()

void gpr::GaussianProcessRegression::setOptimizationSubsetHistory ( int rows)
inlinenoexcept

Rows the hyperparameter optimizer fits on: the farthest-point subset of this many rows (plus the latest points) when the training set is larger, the full set otherwise. Nonpositive means every row. The canonical gprd value is 10, adaptively grown to 30 on detected instability; a 300-row band model then had its theta fitted on 10 rows every outer iteration.

Definition at line 2442 of file GaussianProcessRegression.h.

2443 {
2444 fps_options.history = rows > 0 ? rows : std::numeric_limits<int>::max();
2445 }

◆ setOutputScaleFloor()

void gpr::GaussianProcessRegression::setOutputScaleFloor ( bool enabled)
inlinenoexcept

Floor the output standardization scale at the energy the gradient data imply. A near-flat energy target has a collapsing standard deviation, and dividing the Cartesian gradient by it amplifies the standardized gradient targets without bound; the fixed standardized noise then stops regularizing them. The floor is sqrt(jitter) * rms(abs(G_row)) * rms(abs(R_row - mean R)), an energy built from the gradient scale (eV/A), the spread of the sampled geometries (A) and the model's own relative noise. It raises a collapsing scale only. Default off.

Definition at line 1723 of file GaussianProcessRegression.h.

1724 {
1725 output_scale_floor_ = enabled;
1726 }

◆ setOutputScaleForTesting()

void gpr::GaussianProcessRegression::setOutputScaleForTesting ( double scale)
inlinenoexcept

Definition at line 2841 of file GaussianProcessRegression.h.

2842 {
2843 y_scale_ = scale;
2844 }

◆ setPairLocalDirectionalTiles()

void gpr::GaussianProcessRegression::setPairLocalDirectionalTiles ( bool enabled)
inlinenoexcept

Complete energy/gradient layouts assemble directional curvature from pair tiles, including a zero cutoff, with one owner per tile on distributed layouts. The switch follows the pair-local tiles unless set explicitly. Off, curvature rebuilds every channel-pair block.

Definition at line 1943 of file GaussianProcessRegression.h.

1944 {
1945 use_pair_local_directional_tiles_ = enabled;
1946 }

◆ setPairLocalTiles()

void gpr::GaussianProcessRegression::setPairLocalTiles ( bool enabled)
inlinenoexcept

The pair-local tiles assemble the training covariance and contract its hyperparameter derivatives per configuration pair; off, the per-channel block geometry does both.

Definition at line 1931 of file GaussianProcessRegression.h.

1932 {
1933 use_pair_local_tiles_ = enabled;
1934 }

◆ setParameters() [1/2]

void gpr::GaussianProcessRegression::setParameters ( const Eigen::VectorXd & w)

Set GP parameters. This function sets parameters in the covariance functions sexpat and constant and in the Gaussian likelyhood lik_gaussian.

Parameters
wVector of combined parameters from covariance functions and likelyhood. Used by callers (e.g. OCINEB) that snapshot then restore theta around a sibling phase that would otherwise drift it.

Definition at line 2112 of file GaussianProcessRegression.cpp.

2113{
2114 if (w.rows() == 0) return;
2115 if (atomic_environment_model_) invalidateLikelihoodNoiseDependentState();
2116 pending_hyperparameter_posterior_ = {};
2117
2118#ifndef NDEBUG
2119 gpr::assertMsg(sexpat_cov_func != nullptr,
2120 "Object of Gausian likelihood is not allocated!");
2121 gpr::assertMsg(const_cov_fun != nullptr,
2122 "Object of Gausian likelihood is not allocated!");
2123 gpr::assertMsg(lik_gaussian != nullptr,
2124 "Object of Gausian likelihood is not allocated!");
2125#endif
2126
2127 last_objective_theta_.resize(0);
2128 sexpat_cov_func->setParameters(w);
2129 const_cov_fun->setParameters(w);
2130 lik_gaussian->setParameters(w);
2131 theta_includes_likelihood_noise_ = hasTrailingLikelihoodNoiseParameter(w);
2132 if (theta_includes_likelihood_noise_) {
2133 const double noise = numerics::exp(w(w.rows() - 1));
2134 sigma2 = trainingToPhysicalNoiseVariance(noise);
2135 lik_gaussian->setSigma2(noise);
2136 }
2137}
double exp(double x) noexcept

◆ setParameters() [2/2]

void gpr::GaussianProcessRegression::setParameters ( const GPRSetup & parameters)
inline

Set parameters of the GPR model.

Definition at line 2987 of file GaussianProcessRegression.inl.

2988{
2989 sigma2 = parameters.sigma2;
2990 theta_includes_likelihood_noise_ = false;
2991 jitter_sigma2 = parameters.jitter_sigma2;
2992 optimization_alg = parameters.optimization_alg;
2993 use_ls_prior_ = parameters.ls_prior;
2994 detail::validateRigidNullDeflationConfiguration(
2995 use_rigid_null_deflation_, parameters.principled_nugget);
2996 principled_nugget_ = parameters.principled_nugget;
2997 kappa_max_ = parameters.kappa_max;
2998 scg_opt_settings.map_prior_weight_mode = parameters.map_prior_weight_mode;
2999 scg_opt_settings.map_use_configured_magn_prior =
3000 parameters.map_use_configured_priors;
3001 scg_opt_settings.map_use_configured_lengthscale_prior =
3002 parameters.map_use_configured_priors;
3003 hyperparameter_optimization_mode_ =
3004 (parameters.optimization_alg == INLA_opt)
3007 ++laplace_model_revision_;
3008}
HyperparameterOptimizationMode
Definition Enums.h:56

◆ setPhysicsCollocationPath()

void gpr::GaussianProcessRegression::setPhysicsCollocationPath ( const Coord & path_points)
inline

Physics collocation set for hyperparameter selection: the live band (discrete IRC). When nonempty, the chem-factorized grid rejects hyperparameters whose posterior energy profile along these points oscillates (total variation beyond a scale-free multiple of the profile range), a constrained empirical-Bayes filter in the physics-informed-GP sense. Empty clears the filter.

Definition at line 1187 of file GaussianProcessRegression.h.

1188 {
1189 physics_collocation_path_ = path_points;
1190 }

◆ setPopulationPrior()

void gpr::GaussianProcessRegression::setPopulationPrior ( priors::PopulationPrior prior)
inline

The campaign's population prior on the log length scales per element pair (gpr/prior/PopulationPrior.h): a pair type the population has seen is anchored at its location with its width, both in the kernel's hierarchical prior and in the MAP anchor.

Definition at line 1759 of file GaussianProcessRegression.h.

1760 {
1761 population_prior_ = std::move(prior);
1762 population_prior_reported_ = false;
1763 }

◆ setPrincipledNugget()

void gpr::GaussianProcessRegression::setPrincipledNugget ( bool use)

Definition at line 523 of file GaussianProcessRegression.cpp.

524{
525 detail::validateRigidNullDeflationConfiguration(use_rigid_null_deflation_,
526 use);
527 principled_nugget_ = use;
528}

◆ setPriorMeanStatistic()

void gpr::GaussianProcessRegression::setPriorMeanStatistic ( PriorMeanStatistic statistic)
inlinenoexcept

The constant the GP reverts to away from its data. The mean of the residual energies lets a surrogate relaxation find lower energy in every direction the training rows never varied (a spectator bond compressed inside one length scale reverts toward a mean that sits below the images near the barrier); the maximum makes every such extrapolation uphill, so the band relaxes where the data supports it and the acquisition measures the boundary.

Definition at line 1702 of file GaussianProcessRegression.h.

1703 {
1704 prior_mean_statistic_ = statistic;
1705 }

◆ setProfileEnergySplit()

void gpr::GaussianProcessRegression::setProfileEnergySplit ( bool enabled)
inlinenoexcept

Definition at line 1523 of file GaussianProcessRegression.h.

1524 {
1525 profile_energy_split_ = enabled;
1526 }

◆ setProfileGradientSplit()

void gpr::GaussianProcessRegression::setProfileGradientSplit ( bool enabled)
inlinenoexcept

Definition at line 1532 of file GaussianProcessRegression.h.

1533 {
1534 profile_gradient_split_ = enabled;
1535 }

◆ setProfilePredictMean()

void gpr::GaussianProcessRegression::setProfilePredictMean ( bool enabled)
inlinenoexcept

Definition at line 1514 of file GaussianProcessRegression.h.

1515 {
1516 profile_predict_mean_ = enabled;
1517 }

◆ setRequireScgFallbackImprovement()

void gpr::GaussianProcessRegression::setRequireScgFallbackImprovement ( bool enabled)
noexcept

A dimer search sets this so an L-BFGS recovery that does not lower the MAP objective is discarded and the SCG point is kept. A flat ridge otherwise moves the hyperparameters without a better fit.

Definition at line 5122 of file Optimize.cpp.

5124{
5125 optimizer_state_->require_scg_fallback_improvement = enabled;
5126}

◆ setResidualDiagonalCorrectionForTesting()

void gpr::GaussianProcessRegression::setResidualDiagonalCorrectionForTesting ( bool use,
double eps )
inlinenoexcept

Definition at line 2548 of file GaussianProcessRegression.h.

2549 {
2550 use_correction_ = use;
2551 correction_eps_ = eps;
2552 }

◆ setRetainFittedHyperparameterDensity()

void gpr::GaussianProcessRegression::setRetainFittedHyperparameterDensity ( bool retain)
noexcept

Keep a snapshot of the fitted density after each hyperparameter fit so fittedHyperparameterInformation can describe it. Off by default: a fit then copies no rows, targets or kernel and leaves the distance cache and the slice-Laplace state untouched.

Definition at line 860 of file LaplaceSlice.cpp.

862{
863 retain_fitted_hyperparameter_density_ = retain;
864 if (!retain) fitted_hyperparameter_density_.reset();
865}

◆ setRFFFeaturesRequested()

void gpr::GaussianProcessRegression::setRFFFeaturesRequested ( int D_rff)
inline

Configure the layered RFF predict path. D_rff > 0 enables a fixed count and clears automatic selection. optimize() rebuilds the RFF model on the full observation after each successful SCG fit. 0 disables (default; bit-identical when automatic selection is off).

Definition at line 2190 of file GaussianProcessRegression.h.

2191 {
2192 if (D_rff < 0) {
2193 throw std::invalid_argument(
2194 "rff feature count must be non-negative");
2195 }
2196 rff_features_requested_ = D_rff;
2197 rff_auto_ = false;
2198 }

◆ setRgminInitialLogMove()

void gpr::GaussianProcessRegression::setRgminInitialLogMove ( double distance)
inlinenoexcept

Largest distance, in log-hyperparameter units, the first step of a cold rgmin MAP fit may move the parameters (RgminOpt::setInitialLogMove). Zero leaves the first step to the solver.

Definition at line 2468 of file GaussianProcessRegression.h.

2469 {
2470 rgmin_initial_log_move_ = distance;
2471 }

◆ setRgminInitialLogMoveWholeSession()

void gpr::GaussianProcessRegression::setRgminInitialLogMoveWholeSession ( bool whole_session)
inlinenoexcept

True (default) lowers the opening step of the whole cold session so its first trial moves at most the bound; false caps the first step only.

Definition at line 2479 of file GaussianProcessRegression.h.

2480 {
2481 rgmin_initial_log_move_whole_session_ = whole_session;
2482 }

◆ setRgminMethod()

void gpr::GaussianProcessRegression::setRgminMethod ( rgmin_method_t m)
noexcept

Solver for HyperparameterOptimizationMode::RGMIN_OPT. Applies to the next mode selection as well as the live optimizer, so order of configuration does not matter.

Definition at line 218 of file GaussianProcessRegression.cpp.

219{
220 rgmin_method_ = method;
221 rgmin_method_set_ = true;
222 if (auto* optimizer =
223 std::get_if<funcmin::RgminOpt>(&optimizer_state_->optimizer))
224 optimizer->setMethod(method);
225}

◆ setRgminWarmStart()

void gpr::GaussianProcessRegression::setRgminWarmStart ( bool keep)
inlinenoexcept

Transplant the previous fit's record into the next fit (default true). The record is the accepted steps of the last converged fit as curvature pairs, taken only when the move they propose for the new gradient stays within the opening trust, and dropped when measured rows contradict the posterior (measuredRowsAgreeWithPosterior; funcmin::RgminOpt::setPersistentSession).

Definition at line 2370 of file GaussianProcessRegression.h.

2371 {
2372 rgmin_warm_start_ = keep;
2373 }

◆ setRigidNullDeflation()

void gpr::GaussianProcessRegression::setRigidNullDeflation ( bool enabled)

Opt-in rigid-motion nullspace deflation for free systems.

Default false. When true, projects each free geometry's gradient block onto the orthonormal complement of its rigid motions before Dense or HS-SVD factorization and adds the exact closed-form decoupled noise contribution back to the NLML objective and noise gradient. On free 2-atom Lennard-Jones marginal-likelihood fits, removing the null rigid modes eliminates ~4e-11 rounding drift at step 0 and shifts rgmin SCG+L-BFGS iteration counts (e.g. 28 -> 33, or 38 -> 49 across max_iter=15 restarts).

Definition at line 509 of file GaussianProcessRegression.cpp.

510{
511 detail::validateRigidNullDeflationConfiguration(enabled,
512 principled_nugget_);
513 if (enabled == use_rigid_null_deflation_) return;
516 clearHssvdBasisState();
517 hssvd_basis_ = StableBasisND{};
518 rigid_deflation_diag_ = RigidDeflationDiagnostic{};
519 active_posterior_.reset();
520 ++laplace_model_revision_;
521}

◆ setRobustNu()

void gpr::GaussianProcessRegression::setRobustNu ( double nu)
inlinenoexcept

Robust rows: the Student-t degrees of freedom of the per- configuration observation model, fitted as a Gaussian scale mixture by one EM sweep per full-data rebuild (0 keeps the Gaussian likelihood).

Definition at line 1817 of file GaussianProcessRegression.h.

1818 {
1819 robust_nu_ = std::isfinite(nu) && nu > 0.0 ? nu : 0.0;
1820 }

◆ setScalapackBlockSize()

void gpr::GaussianProcessRegression::setScalapackBlockSize ( int block_size)
inlinenoexcept

Definition at line 2053 of file GaussianProcessRegression.h.

2054 {
2055 scalapack_block_size_ = block_size;
2056 configureDistributedTrainingGrid();
2057 }

◆ setScalapackNprow()

void gpr::GaussianProcessRegression::setScalapackNprow ( int nprow)
inlinenoexcept

Definition at line 2063 of file GaussianProcessRegression.h.

2064 {
2065 scalapack_nprow_ = nprow;
2066 configureDistributedTrainingGrid();
2067 }

◆ setScgDampingLimitForTesting()

void gpr::GaussianProcessRegression::setScgDampingLimitForTesting ( double limit)
inlinenoexcept

Definition at line 2559 of file GaussianProcessRegression.h.

2560 {
2561 scg_opt_settings.lambda_limit = limit;
2562 }

◆ setScgMaxIterationsForTesting()

void gpr::GaussianProcessRegression::setScgMaxIterationsForTesting ( Index_t max_iter)
inlinenoexcept

Definition at line 2526 of file GaussianProcessRegression.h.

2527 {
2528 scg_opt_settings.common.max_iter = max_iter;
2529 }

◆ setSecantQuadraticPrior()

void gpr::GaussianProcessRegression::setSecantQuadraticPrior ( const Eigen::VectorXd & position,
const Eigen::VectorXd & gradient,
const Eigen::MatrixXd & hessian,
double reference_energy )

Quadratic mean carried by an accepted true-force secant. When a ZBL or Morse prior is already active the quadratic is the residual of that prior, and the two add: m(x) = m_prior(x) + q(x).

Definition at line 807 of file GaussianProcessRegression.cpp.

810{
811 if (position.size() == 0 || gradient.size() != position.size() ||
812 hessian.rows() != position.size() ||
813 hessian.cols() != position.size() || !position.allFinite() ||
814 !gradient.allFinite() || !hessian.allFinite() ||
815 !std::isfinite(reference_energy))
816 throw std::invalid_argument(
817 "secant quadratic mean requires a finite matching Hessian");
818 secant_reference_position_ = position;
819 secant_reference_gradient_ = gradient;
820 secant_hessian_ = 0.5 * (hessian + hessian.transpose());
821 secant_reference_energy_ = reference_energy;
822 secant_quadratic_prior_active_ = true;
823}

◆ setSkipUnchangedSubsetFit()

void gpr::GaussianProcessRegression::setSkipUnchangedSubsetFit ( bool enabled)
inlinenoexcept

Skip a hyperparameter fit whose objective the previous converged fit already minimized. The fitted theta depends on the fit subset and the start only: when an append leaves the selected rows unchanged and the model still holds the theta that fit returned, the fit has nothing to minimize and the new rows are conditioned at that theta. Default off.

Definition at line 2488 of file GaussianProcessRegression.h.

2489 {
2490 skip_unchanged_subset_fit_ = enabled;
2491 }

◆ setSliceLaplaceHessianCholForTesting()

void gpr::GaussianProcessRegression::setSliceLaplaceHessianCholForTesting ( const Eigen::MatrixXd & U)

Definition at line 4124 of file Optimize.cpp.

4126{
4127 laplace_posterior_.reset();
4128 slice_laplace_state_ = std::make_unique<SliceLaplaceState>();
4129 slice_laplace_state_->hessian_chol_U = U;
4130 slice_laplace_state_->valid = U.rows() > 0 && U.rows() == U.cols();
4131}

◆ setSubsetFailureEscalation()

void gpr::GaussianProcessRegression::setSubsetFailureEscalation ( bool enabled)
inlinenoexcept

Policy for a subset fit that does not converge. True (default) refits on every retained row with every length scale active, which swaps the estimator for a different objective. False keeps the subset estimator: the feasible improvement (or the input theta) stands, and the all-rows fit runs only when the subset objective is not evaluable at either point, since the subset then carries no likelihood to optimize.

Definition at line 2457 of file GaussianProcessRegression.h.

2458 {
2459 subset_failure_escalation_ = enabled;
2460 }

◆ setSVGDConfig()

void gpr::GaussianProcessRegression::setSVGDConfig ( const laplace::SteinVariationalConfig & cfg)
inlinenoexcept

SVGD config getters/setters. Default-constructed SteinVariationalConfig matches the prior hardcoded literals (T=30, eps=0.05, conv_tol=1e-3) so existing callers stay bit-identical until they opt in.

Definition at line 4422 of file GaussianProcessRegression.h.

4423 {
4424 svgd_config_ = cfg;
4425 }

◆ setUncertaintyMode()

void gpr::GaussianProcessRegression::setUncertaintyMode ( UncertaintyMode mode)
inline

Select which predictive path consumers should use. Default MAP matches the pre-Laplace behaviour bit-for-bit; LAPLACE routes through calculatePotentialLaplace (CCD mixture), BMA is reserved for the reference path (not yet wired).

Definition at line 1356 of file GaussianProcessRegression.h.

1357 {
1358 uncertainty_mode_ = mode;
1359 }

◆ setUpDefault()

void gpr::GaussianProcessRegression::setUpDefault ( )

Set up default parameters.

This function allocates memory for the private pointers and calls for setUpDefault() method on each pointer.

◆ setUseAlphaKLaplaceMean()

void gpr::GaussianProcessRegression::setUseAlphaKLaplaceMean ( bool use)
inlinenoexcept

Enable the alpha-K contraction for Laplace-mixture mean prediction.

Definition at line 1406 of file GaussianProcessRegression.h.

1407 {
1408 use_alpha_k_laplace_mean_ = use;
1409 }

◆ setUseAlphaKPredictMean()

void gpr::GaussianProcessRegression::setUseAlphaKPredictMean ( bool use)
inlinenoexcept

Enable the alpha-K contraction for MAP mean prediction.

Definition at line 1396 of file GaussianProcessRegression.h.

1397 {
1398 use_alpha_k_predict_mean_ = use;
1399 }

◆ setUseDeltaMethod()

void gpr::GaussianProcessRegression::setUseDeltaMethod ( bool use)
inlinenoexcept

Switch the LAPLACE_SLICE arm to the analytical INLA-Delta variance estimator (Rue 2009 sec 3.2; GPstuff INLA mode 0 'gaussian'). Replaces the per-call sampling/quadrature loop with the closed-form formula: Var[mu(x*) | y] = Var_MAP(x*) + g(x*)^T H^{-1} g(x*), g(x*)_j ~= k_cross^T dalpha/dtheta_j. SymPy proof D1-D7 in python/tests/test_sympy_inla_delta.py. Per-call cost O(p N n_q) (no per-call Cholesky); the slice/ PSIS sampling burst is skipped entirely.

Definition at line 2121 of file GaussianProcessRegression.h.

2122 {
2123 use_delta_method_ = use;
2124 }

◆ setUseFFPriorMean()

void gpr::GaussianProcessRegression::setUseFFPriorMean ( bool use)
inline

Teng/Bao first-level Morse force-field prior mean. Default off. Mutually exclusive with ZBL at evaluation: Morse wins if both flags are set so the residual is not ZBL+Morse stacked.

Definition at line 1977 of file GaussianProcessRegression.h.

1978 {
1979 use_ff_prior_mean_ = use;
1980 configureFFPriorMean(atoms_config);
1981 }

◆ setUseLogNormalMagnPrior()

void gpr::GaussianProcessRegression::setUseLogNormalMagnPrior ( bool use)
inlinenoexcept

Opt-in log-normal prior on magnSigma2 (PriorLogNormal). Off keeps the half-Student-t or half-Cauchy magnitude prior.

Definition at line 1785 of file GaussianProcessRegression.h.

1786 {
1787 scg_opt_settings.map_use_lognormal_magn_prior = use;
1788 if (sexpat_cov_func) sexpat_cov_func->setUseLogNormalMagnPrior(use);
1789 }

◆ setUseLsPrior()

void gpr::GaussianProcessRegression::setUseLsPrior ( bool use)
inlinenoexcept

Definition at line 1775 of file GaussianProcessRegression.h.

1776 {
1777 use_ls_prior_ = use;
1778 }

◆ setUsePrecisionMatrix()

void gpr::GaussianProcessRegression::setUsePrecisionMatrix ( bool use)
inline

Select explicit precision algebra for the direct Cholesky posterior. Posterior means materialize the inverse from the active factor at each use. Posterior variances solve against that factor and do not form it. The inverse is dense and is not retained across objective or posterior changes.

Definition at line 4107 of file GaussianProcessRegression.h.

4108 {
4109 use_precision_ = use;
4110 }

◆ setUsePsisDeterministicGrid()

void gpr::GaussianProcessRegression::setUsePsisDeterministicGrid ( bool use)
inlinenoexcept

Switch the PSIS-Laplace sampler between random IS draws (default, false) and a deterministic axial CCD-style grid (true) of K = 1 + 2 p nodes placed at theta_MAP +/- sigma_j e_j on the principal axes of H^{-1}. Deterministic grid is np-reproducible; random IS retains MC variance per rank. Standard INLA Gaussian-mode quadrature (Rue 2009 sec 3.2, GPstuff INLA mode 0).

Definition at line 2103 of file GaussianProcessRegression.h.

2104 {
2105 psis_laplace_opts_.deterministic_axial_grid = use;
2106 }

◆ setUsePsisLaplace()

void gpr::GaussianProcessRegression::setUsePsisLaplace ( bool use)
inlinenoexcept

Switch the LAPLACE_SLICE arm between the doubling slice sampler (default, false) and the PSIS-Laplace sampler (Vehtari 2024, arXiv:1507.02646 v9). PSIS-Laplace replaces the slice's M*~5 Cholesky burst with K Cholesky decomps + a Pareto k_hat reliability check.

Definition at line 2087 of file GaussianProcessRegression.h.

2088 {
2089 use_psis_laplace_ = use;
2090 }

◆ setUseTrainingGeometryHandle()

void gpr::GaussianProcessRegression::setUseTrainingGeometryHandle ( bool use)
inlinenoexcept

Definition at line 1505 of file GaussianProcessRegression.h.

1506 {
1507 use_training_geometry_handle_ = use;
1508 }

◆ setUseZBLPriorMean()

void gpr::GaussianProcessRegression::setUseZBLPriorMean ( bool use)
inline

Definition at line 1964 of file GaussianProcessRegression.h.

1965 {
1966 use_zbl_prior_mean_ = use;
1967 configureZBLPriorMean(atoms_config);
1968 }

◆ setVarianceConvention()

void gpr::GaussianProcessRegression::setVarianceConvention ( VarianceConvention convention)
inlinenoexcept

Definition at line 3006 of file GaussianProcessRegression.h.

3007 {
3008 variance_convention_ = convention;
3009 }

◆ setVarianceSubsetConfigurationIds()

void gpr::GaussianProcessRegression::setVarianceSubsetConfigurationIds ( std::vector< int > ids)
inline

Definition at line 2274 of file GaussianProcessRegression.h.

2275 {
2276 std::sort(ids.begin(), ids.end());
2277 ids.erase(std::unique(ids.begin(), ids.end()), ids.end());
2278 variance_subset_forced_ids_ = std::move(ids);
2279 }

◆ setVarianceSubsetConfigurations()

void gpr::GaussianProcessRegression::setVarianceSubsetConfigurations ( int configurations)
inlinenoexcept

Posterior covariance conditioned on the training configurations nearest the query only (all channels of the m nearest in the pair-distance metric): the exact posterior of a GP that has seen a subset of the data, an upper bound in the Loewner order on the full posterior, at a cost in m rather than in the training size. Zero keeps the full solve. The subset factor is cached across the queries of one factor epoch that select the same configurations.

Definition at line 2257 of file GaussianProcessRegression.h.

2258 {
2259 variance_subset_configurations_ = std::max(0, configurations);
2260 }

◆ setVarianceSubsetFootprint()

void gpr::GaussianProcessRegression::setVarianceSubsetFootprint ( bool enabled)
inlinenoexcept

The configurations the subset posterior conditions on, chosen by the caller (the search footprint: every configuration the search measured and the seeds within their radius); empty falls back to the nearest-N rule above. The dimer supplies its search footprint as the subset.

Definition at line 2266 of file GaussianProcessRegression.h.

2267 {
2268 variance_subset_footprint_ = enabled;
2269 }

◆ setWallClockLimit()

void gpr::GaussianProcessRegression::setWallClockLimit ( std::shared_ptr< const WallClockLimit > limit)
inline

Share the enclosing search deadline with every hyperparameter optimizer. A null limit removes the callback.

Definition at line 2532 of file GaussianProcessRegression.h.

2533 {
2534 wall_clock_limit_ = std::move(limit);
2535 scg_opt_settings.common.stop_requested =
2536 wall_clock_limit_
2537 ? std::function<bool()>([limit = wall_clock_limit_,
2538 execution = backend_context_] {
2539 return optimizationDeadlineReached(limit, execution);
2540 })
2541 : std::function<bool()>{};
2542 }

◆ skipUnchangedSubsetFit()

bool gpr::GaussianProcessRegression::skipUnchangedSubsetFit ( ) const
inlinenodiscardnoexcept

Definition at line 2492 of file GaussianProcessRegression.h.

2493 {
2494 return skip_unchanged_subset_fit_;
2495 }

◆ solveTrainingCovarianceInFactorLayout()

Eigen::VectorXd gpr::GaussianProcessRegression::solveTrainingCovarianceInFactorLayout ( const Eigen::VectorXd & rhs) const
nodiscard

Solve the training covariance with RHS and result in factor order. Callers supplying derivative matrices use symmetricMatrixInTrainingFactorLayout.

Definition at line 276 of file Decompose.cpp.

278{
279 if (!hasTrainingCholeskyFactor(rhs.size()))
280 throw std::logic_error("training covariance factor is unavailable");
281 if (rigid_deflation_.isActiveForFullOrder(rhs.size())) {
282 const Eigen::VectorXd rhs_r = rigid_deflation_.projectVector(rhs);
283 const Eigen::VectorXd solved_r = trainingSolver().solve(rhs_r);
284 return rigid_deflation_.liftSolvedVector(rhs, solved_r);
285 }
286 return trainingSolver().solve(rhs);
287}

◆ subsetFailureEscalation()

bool gpr::GaussianProcessRegression::subsetFailureEscalation ( ) const
inlinenodiscardnoexcept

Definition at line 2461 of file GaussianProcessRegression.h.

2462 {
2463 return subset_failure_escalation_;
2464 }

◆ supportsRigidNullDeflation()

virtual bool gpr::GaussianProcessRegression::supportsRigidNullDeflation ( ) const
inlinenodiscardprotectedvirtualnoexcept

Reimplemented in gpr::StudentTProcessRegression.

Definition at line 5572 of file GaussianProcessRegression.h.

5573 {
5574 return true;
5575 }

◆ symmetricMatrixInTrainingFactorLayout()

EigenMatrix gpr::GaussianProcessRegression::symmetricMatrixInTrainingFactorLayout ( const EigenMatrix & input) const
nodiscard

Definition at line 1150 of file GaussianProcessRegression.cpp.

1152{
1153 if (!hasTrainingPermutation()) return input;
1155}

◆ synchronizeOutputTransformFrom()

void gpr::GaussianProcessRegression::synchronizeOutputTransformFrom ( const GaussianProcessRegression & source)

Use the same affine output coordinates as another GP.

Local and global posteriors that share kernel parameters must also condition on the same residual target E - mean(E). Otherwise changing model ownership changes both the predicted energy and, through the posterior coefficients, its Cartesian gradient.

Definition at line 2087 of file GaussianProcessRegression.cpp.

2089{
2090 restoreOutputTransform(source.y_mean_, source.y_scale_,
2091 source.y_mean_frozen_);
2092}
void restoreOutputTransform(double mean, double scale, bool frozen_mean)
Restore output coordinates alongside a kernel represented in them.

◆ tieLengthScaleParameters()

void gpr::GaussianProcessRegression::tieLengthScaleParameters ( Eigen::VectorXd & theta) const

Sets every tied member to its leader's log length (theta(1 + t)).

Definition at line 739 of file GaussianProcessRegression.cpp.

741{
742 const auto& ties = length_scale_ties_;
743 if (!use_length_scale_ties_ || !ties.valid ||
744 theta.size() < 1 + ties.count())
745 return;
746 for (Index_t t = 0; t < ties.count(); ++t)
747 theta(1 + t) = theta(1 + ties.leader[static_cast<std::size_t>(t)]);
748}

◆ totalPosteriorNoiseVarianceForTesting()

double gpr::GaussianProcessRegression::totalPosteriorNoiseVarianceForTesting ( ) const
inlinenodiscardnoexcept

Definition at line 2855 of file GaussianProcessRegression.h.

2856 {
2857 return totalPosteriorNoiseVariance();
2858 }

◆ traceInverseProduct()

double gpr::GaussianProcessRegression::traceInverseProduct ( const EigenMatrix & factor,
const EigenMatrix & observation_order,
const detail::RigidDeflationState * deflation_override = nullptr ) const
nodiscard

tr(K^{-1} A) through the training factor. A is in observation order.

Definition at line 2370 of file EnergyGradient.cpp.

2373{
2374 if (observation_order.rows() != observation_order.cols())
2375 return std::numeric_limits<double>::quiet_NaN();
2376 const detail::RigidDeflationState& active_deflation =
2377 deflation_override != nullptr ? *deflation_override : rigid_deflation_;
2378 if (active_deflation.isActiveForFullOrder(observation_order.rows()) &&
2379 factor.rows() == active_deflation.deflated_rows &&
2380 factor.cols() == active_deflation.deflated_rows) {
2381 EigenMatrix factor_order = observation_order;
2382 if (hasTrainingPermutation() &&
2383 static_cast<Eigen::Index>(training_permutation_.perm.size()) ==
2384 observation_order.rows()) {
2385 factor_order = gpr::permuteSymmetricMatrix(observation_order,
2387 }
2389 factor, active_deflation.projectSymmetric(factor_order));
2390 }
2391 if (factor.rows() != observation_order.rows() ||
2392 factor.cols() != observation_order.cols())
2393 return std::numeric_limits<double>::quiet_NaN();
2394 if (hasTrainingPermutation() &&
2395 static_cast<Eigen::Index>(training_permutation_.perm.size()) ==
2396 factor.rows()) {
2398 factor, gpr::permuteSymmetricMatrix(observation_order,
2400 }
2401 return linalg::trace_solve_product(factor, observation_order);
2402}
double trace_solve_product(const EigenMatrix &L, const EigenMatrix &A)

◆ trainingCholeskyDiagonal()

Eigen::VectorXd gpr::GaussianProcessRegression::trainingCholeskyDiagonal ( ) const
nodiscardprotected

Definition at line 493 of file Predict.cpp.

494{
495 const Eigen::Index order = a.size();
496 if (!hasTrainingCholeskyFactor(order)) return {};
497 if (L.rows() == order && L.cols() == order) return L.diagonal();
498#ifdef GPR_LINALG_SCALAPACK
499 auto& state = backend().distributed();
500 Eigen::VectorXd diagonal = Eigen::VectorXd::Zero(order);
501 const int* descriptor = state.cached_L_desc();
502 for (int i = 0; i < order; ++i) {
503 const int owner_row = (i / state.block_size()) % state.nprow();
504 const int owner_col = (i / state.block_size()) % state.npcol();
505 if (owner_row != state.myrow() || owner_col != state.mycol()) continue;
506 const int row = state.local_index_for_global(
507 i, state.block_size(), state.myrow(), state.nprow());
508 const int column = state.local_index_for_global(
509 i, state.block_size(), state.mycol(), state.npcol());
510 diagonal(i) = state.cached_L()[row + static_cast<std::size_t>(column) *
511 descriptor[8]];
512 }
513 if (state.nprocs() > 1)
514 MPI_Allreduce(MPI_IN_PLACE, diagonal.data(), static_cast<int>(order),
515 MPI_DOUBLE, MPI_SUM, state.world_comm());
516 return diagonal;
517#else
518 return {};
519#endif
520}

◆ trainingCovarianceForTesting()

EigenMatrix gpr::GaussianProcessRegression::trainingCovarianceForTesting ( ) const
inlinenodiscard

The training covariance C. Under a resident device posterior the host matrix is not kept; L L^T of the downloaded factor stands in and reproduces C to the rounding of the factorization.

Definition at line 2748 of file GaussianProcessRegression.h.

2749 {
2750#ifdef GPR_LINALG_KOKKOS
2751 if (hasDevicePosterior()) {
2752 const EigenMatrix lower =
2753 getL().template triangularView<Eigen::Lower>();
2754 return lower * lower.transpose();
2755 }
2756#endif
2757 return C;
2758 }

◆ trainingCrossCovarianceInFactorRows()

EigenMatrix gpr::GaussianProcessRegression::trainingCrossCovarianceInFactorRows ( const EigenMatrix & query,
const Eigen::VectorXd & query_ind,
bool serial_per_rank ) const
nodiscard

The cross-covariance in factor rows, placed when it can be and assembled channel-major and permuted otherwise.

Definition at line 2482 of file CovarianceAssembly.cpp.

2485{
2486 EigenMatrix cross;
2487 if (evaluateTrainingCrossCovarianceInFactorOrder(query, query_ind, cross))
2488 return cross;
2489 evaluateCovarianceMatrix(R_matrix, query, R_indices, query_ind, cross,
2490 serial_per_rank);
2491 return permuteTrainingRows(cross);
2492}
bool evaluateTrainingCrossCovarianceInFactorOrder(const EigenMatrix &query, const Eigen::VectorXd &query_ind, EigenMatrix &cross) const

◆ trainingFactorAppendable()

bool gpr::GaussianProcessRegression::trainingFactorAppendable ( Eigen::Index observations) const

Has a full or conditional hyperparameter fit been accepted? Trust decisions require a fitted posterior with calibrated parameters. True when a full-data rebuild on ~observations~ configurations would append to the cached distributed factor instead of refactorizing: the factor is live, the design grows, and the kernel parameters are those it was built with.

Definition at line 3148 of file Decompose.cpp.

3150{
3151#ifdef GPR_LINALG_KOKKOS
3153 !principled_nugget_) {
3154 if (!device_posterior_->matchesConfiguration(
3155 sexpat_cov_func->getConfInfo(),
3156 sexpat_cov_func->farFieldRadius()))
3157 return false;
3158 const auto& lengths = sexpat_cov_func->getLengthScaleRef();
3159 return device_posterior_->canAppend(
3160 observations,
3161 lik_gaussian->evaluateTrainingVariance(
3162 device_posterior_->trainingRows()),
3163 Eigen::Map<const Eigen::VectorXd>(lengths.data(), lengths.size()),
3164 sexpat_cov_func->getMagnSigma2(), const_cov_fun->getConstSigma2(),
3165 jitter_sigma2);
3166 }
3167#endif
3168#ifdef GPR_LINALG_SCALAPACK
3169 const auto& signature = distributed_factor_signature_;
3170 if (!signature.valid || sexpat_cov_func == nullptr ||
3171 signature.rows.rows() <= 0 || !training_cholesky_is_distributed_ ||
3172 use_correction_ || principled_nugget_ ||
3173 signature.nugget_coefficient != 0.0 ||
3174 sexpat_cov_func->usesManifoldChart() ||
3175 sexpat_cov_func->usesGeodesicHeatKernel() ||
3176 signature.configured_jitter != jitter_sigma2 ||
3177 !detail::sameSexpatGeometry(
3178 signature.kernel_configuration, sexpat_cov_func->getConfInfo(),
3179 signature.far_field_radius, sexpat_cov_func->farFieldRadius()))
3180 return false;
3181 return observations > signature.observations &&
3182 signature.theta == sexpat_cov_func->combineParameters();
3183#else
3184 const auto& signature = serial_factor_signature_;
3185 const Eigen::Index rows = signature.rows.rows();
3186 if (!signature.valid || rows <= 0 || signature.indices.size() != rows ||
3187 !signature.indices.allFinite())
3188 return false;
3189 const Eigen::Index channels =
3190 detail::storedObservationChannelCount(signature.indices);
3191 if (channels <= 0 || rows % channels != 0) return false;
3192 for (Eigen::Index row = channels; row < rows; ++row)
3193 if (signature.indices(row) != signature.indices(row % channels))
3194 return false;
3195 const Eigen::Index expected_rows = activeFactorOrder(rows);
3196 if (observations <= rows / channels || sexpat_cov_func == nullptr ||
3197 lik_gaussian == nullptr || use_correction_ || principled_nugget_ ||
3198 signature.nugget_coefficient != 0.0 || signature.manifold_chart ||
3199 sexpat_cov_func->usesManifoldChart() ||
3200 signature.geodesic_heat != sexpat_cov_func->usesGeodesicHeatKernel() ||
3201 signature.heat_identity != sexpat_cov_func->geodesicHeatKernel() ||
3202 signature.jitter_sigma2 != jitter_sigma2 ||
3203 signature.theta != sexpat_cov_func->combineParameters() ||
3205 !detail::sameSexpatGeometry(
3206 signature.kernel_geometry, sexpat_cov_func->getConfInfo(),
3207 signature.far_field_radius, sexpat_cov_func->farFieldRadius()) ||
3208 L.rows() != expected_rows || L.cols() != expected_rows ||
3209 C.rows() != expected_rows || C.cols() != expected_rows ||
3210 signature.indices.size() != rows || signature.constant.size() != rows ||
3211 signature.noise.size() != rows)
3212 return false;
3213 const Eigen::VectorXd noise =
3214 lik_gaussian->evaluateTrainingVariance(signature.rows);
3215 const Eigen::VectorXd constant = detail::constantCovarianceUpdate(
3216 const_cov_fun.get(), signature.indices);
3217 return noise == signature.noise && constant == signature.constant;
3218#endif
3219}

◆ trainingGeometryApplyCallsForTesting()

std::size_t gpr::GaussianProcessRegression::trainingGeometryApplyCallsForTesting ( ) const
inlinenodiscard

Definition at line 846 of file GaussianProcessRegression.h.

847 {
848 return training_geometry_apply_calls_for_testing_;
849 }

◆ trainingInverseDiagonalForTesting()

Eigen::VectorXd gpr::GaussianProcessRegression::trainingInverseDiagonalForTesting ( ) const
inlinenodiscard

Definition at line 2773 of file GaussianProcessRegression.h.

◆ trainingInverseDiagonalInFactorLayout()

const Eigen::VectorXd & gpr::GaussianProcessRegression::trainingInverseDiagonalInFactorLayout ( ) const
nodiscardprotected

Definition at line 523 of file Predict.cpp.

524{
525#ifdef GPR_LINALG_KOKKOS
526 if (hasDevicePosterior()) {
527 if (training_inverse_diagonal_.size() != device_posterior_->order()) {
529 device_posterior_->downloadInverseDiagonal();
530 ++inverse_diagonal_builds_for_testing_;
531 }
533 }
534#endif
535 if (training_inverse_diagonal_.size() == a.size() ||
538#ifdef GPR_LINALG_SCALAPACK
539 if (training_cholesky_is_distributed_) {
541 backend().cholesky_inverse_diagonal_distributed(
542 L, static_cast<int>(a.size()));
543 } else {
544 const EigenMatrix inverse_factor =
545 L.template triangularView<Eigen::Lower>().solve(
546 EigenMatrix::Identity(a.size(), a.size()));
548 inverse_factor.colwise().squaredNorm().transpose();
549 }
550#else
551 if (rigid_deflation_.isActiveForFullOrder(a.size())) {
553 rigid_deflation_.fullInverseDiagonalFromFactor(L);
554 } else {
556 EigenMatrix::Identity(a.size(), a.size()));
557 }
558#endif
559 ++inverse_diagonal_builds_for_testing_;
561}

◆ trainingPermutationForTesting()

const StructuredPermutation & gpr::GaussianProcessRegression::trainingPermutationForTesting ( ) const
inlinenodiscardnoexcept

Definition at line 2924 of file GaussianProcessRegression.h.

2926 {
2927 return training_permutation_;
2928 }

◆ trainingSolver()

linalg::linop::DenseCholeskySolver gpr::GaussianProcessRegression::trainingSolver ( ) const
inlinenodiscardprotected

The training Gram through the operator layer's dense Cholesky backend, on the current factor L.

Definition at line 5291 of file GaussianProcessRegression.h.

5292 {
5294 }

◆ tryBorderedNoiseReport()

bool gpr::GaussianProcessRegression::tryBorderedNoiseReport ( BorderedNoiseReport & report) const
nodiscard

The noise the trained factor conditions on (likelihood variance plus jitter, condition-floored), the certificate gap eps_k - lambda_min_cert of the exact-kernel factor, and the noise the interval certifies. Returns false when the interval is unsupported; throws std::runtime_error when the factor cannot be built.

Definition at line 810 of file Variance.cpp.

812{
813 if (!canCertifyEnergyVarianceInterval()) return false;
814 // The report is in gpr_model_get_sigma2 units: y_scale^2 only. The LOO
815 // calibration rescales predicted variance, never the noise or the
816 // certificate gap. y_scale = 1 is disabled normalization, where the units
817 // coincide. Any other scale that is not finite and positive with a normal
818 // square has no units to report in, and is rejected instead of reporting
819 // the training-unit values as physical ones. The scale stays in the
820 // working type, as in the energy gate: the report is decided from the
821 // enclosure of y_scale^2, never from a binary64 y_scale * y_scale, and an
822 // enclosure that is not positive and finite certifies nothing.
823 if (!outputScaleConvertsUnits())
824 throw std::domain_error(
825 "the noise floor report needs a finite positive output scale "
826 "whose square is a normal binary64");
827 const double y_scale = y_scale_;
829 y_scale, 1.0)
830 .valid)
831 return false;
832 report = hssvd_basis_.borderedNoiseReport(totalPosteriorNoiseVariance(),
833 y_scale, 1.0);
834 return true;
835}
bool canCertifyEnergyVarianceInterval() const
Definition Variance.cpp:799
VarianceScaleEnclosure< Work > varianceScaleEnclosure(double y_scale, double calibration)

◆ tryDeflateFactorSignalCovariance()

bool gpr::GaussianProcessRegression::tryDeflateFactorSignalCovariance ( const EigenMatrix & x_ordered,
const Eigen::VectorXd & ind_ordered,
const Eigen::VectorXd & noise_ordered,
double extra_uniform_noise,
EigenMatrix & signal_cov,
const Eigen::VectorXd & constant_update,
Eigen::VectorXd & factor_constant,
bool factor_order = true )
protected

Definition at line 2875 of file CovarianceAssembly.cpp.

2880{
2881 const bool unsupported =
2883 lik_gaussian == nullptr || sexpat_cov_func->usesManifoldChart() ||
2884 sexpat_cov_func->usesGeodesicHeatKernel() || principled_nugget_;
2885 const AtomsConfiguration& effective_conf =
2886 (sexpat_cov_func != nullptr &&
2887 sexpat_cov_func->getConfInfo().atoms_mov.type.size() > 0)
2888 ? sexpat_cov_func->getConfInfo()
2889 : atoms_config;
2890
2891 if (!detail::prepareRigidDeflationState(
2892 use_rigid_null_deflation_, factor_order, effective_conf, x_ordered,
2893 ind_ordered, noise_ordered, extra_uniform_noise, unsupported,
2895 rigid_deflation_.reset();
2896 if (report_level >= 2) {
2897 log_man << "Rigid-null deflation skipped: reason="
2898 << rigid_deflation_diag_.reason
2899 << " full_rows=" << rigid_deflation_diag_.full_rows
2900 << ".\n";
2901 }
2902 return false;
2903 }
2904
2905 if (!detail::verifySignalKernelRigidNullspace(signal_cov, rigid_deflation_,
2907 rigid_deflation_.reset();
2908 if (report_level >= 2) {
2909 log_man << "Rigid-null deflation skipped: reason="
2910 << rigid_deflation_diag_.reason << " kr_rel="
2911 << rigid_deflation_diag_.kernel_relative_null_norm << ".\n";
2912 }
2913 return false;
2914 }
2915
2916 signal_cov = rigid_deflation_.projectSymmetric(signal_cov);
2917 if (factor_order) {
2918 for (Eigen::Index i = 0; i < rigid_deflation_.num_geometries; ++i) {
2919 const auto& blk =
2920 rigid_deflation_.blocks[static_cast<std::size_t>(i)];
2921 signal_cov(blk.deflated_row_offset, blk.deflated_row_offset) +=
2922 noise_ordered(blk.full_row_offset) + extra_uniform_noise;
2923 if (blk.deflated_grad_dim > 0) {
2924 signal_cov.diagonal()
2925 .segment(blk.deflated_row_offset + 1, blk.deflated_grad_dim)
2926 .array() += blk.grad_noise_variance;
2927 }
2928 }
2929 if (constant_update.size() == x_ordered.rows()) {
2930 factor_constant = rigid_deflation_.projectVector(constant_update);
2931 }
2932 }
2933 rigid_deflation_.active = true;
2934 if (report_level >= 2) {
2935 log_man << "Rigid-null deflation applied: reason="
2936 << rigid_deflation_diag_.reason
2937 << " rows=" << rigid_deflation_diag_.full_rows << "->"
2938 << rigid_deflation_diag_.deflated_rows
2939 << " rigid_modes=" << rigid_deflation_diag_.rigid_modes
2940 << " kr_rel=" << rigid_deflation_diag_.kernel_relative_null_norm
2941 << ".\n";
2942 }
2943 return true;
2944}

◆ tryGateEnergyVariance()

bool gpr::GaussianProcessRegression::tryGateEnergyVariance ( const Observation & query,
Eigen::RowVectorXd & energy_variance )
nodiscard

Energy-channel posterior variance from a cached factorization.

Assembles only the energy (index-0) query block, so the cross-covariance is n_atoms columns rather than n_atoms*(D+1). That is the cheap Pmat the ActiveGP force() gate needs: if this returns false the caller must use calculateVariance (exact Amat). Distributed-only ScaLAPACK L is refused so the path never issues a collective to answer a point query. HS-SVD uses the cached basis and applies the same LOO calibration factor as calculateVarianceHssvd.

Definition at line 604 of file Variance.cpp.

606{
607 ScopedVarianceTimer variance_timer;
608 energy_variance.resize(0);
609 const Index_t n = query.R.rows();
610 const Index_t D = query.R.cols();
611 if (n <= 0 || D <= 0) return false;
612 if (atomic_environment_model_) {
614 throw std::logic_error(
615 "atomic environment posterior requires conditioning with the "
616 "selected state");
617 atomic_environment_posterior_->calculateEnergyVariance(query.R,
618 energy_variance);
619 if (variance_convention_ == VarianceConvention::Predictive)
620 energy_variance.array() +=
621 trainingToPhysicalNoiseVariance(lik_gaussian->getSigma2());
622 energy_variance *= reportedVarianceCalibrationFactor();
623 return energy_variance.allFinite();
624 }
625 if (R_matrix.rows() <= 0 || R_indices.size() != R_matrix.rows())
626 return false;
627
628 const auto joint_marginal = [&]() {
629 Observation probe;
630 probe.R = query.R;
632 if (probe.E.rows() <= 0 || probe.E.cols() != n) return false;
633 energy_variance = probe.E.row(0);
634 return energy_variance.allFinite();
635 };
636 // A Cartesian MAP posterior needs only the query energy columns of its
637 // joint training covariance. Descriptor charts and mixture posteriors
638 // provide their marginal through their corresponding full operators.
639 if (active_posterior_) {
640 Eigen::VectorXd energy;
641 if (tryActivePosteriorEnergyVariance(query.R, energy) &&
642 energy.size() == n) {
643 energy_variance = energy.transpose();
644 return energy_variance.allFinite();
645 }
646 return joint_marginal();
647 }
648 if ((sexpat_cov_func && sexpat_cov_func->usesManifoldChart()) ||
649 (rff_replaces_exact_ && rff_model_.isBuilt()) ||
650 uncertainty_mode_ != UncertaintyMode::MAP)
651 return joint_marginal();
652
653 EigenMatrix R_e = query.R;
654 Eigen::VectorXd R_e_ind = Eigen::VectorXd::Zero(n);
655
656 if (canUseHssvdVariance()) {
657 // Same model as calculateVarianceHssvd: the dual (descriptor) kernel
658 // when the basis was built on it, else the Cartesian kernel.
659 EigenMatrix Kstar;
660 Eigen::VectorXd prior_diag;
661 if (assembleHssvdDualCrossCovariance(R_e, Kstar, &prior_diag,
662 /*energy_only=*/true)) {
663 priorFromKernelDiagonal(R_e, prior_diag);
664 } else {
665 evaluateCovarianceMatrix(R_matrix, R_e, R_indices, R_e_ind, Kstar,
666 /*serial_per_rank=*/true);
667 EigenMatrix cov_matrix;
668 evaluateTrainingCovarianceMatrix(R_e, R_e_ind, cov_matrix,
669 /*serial_per_rank=*/true);
670 if (cov_matrix.rows() != n || cov_matrix.cols() != n) return false;
671 prior_diag = cov_matrix.diagonal();
672 priorFromTrainingDiagonal(R_e, prior_diag);
673 }
674 if (Kstar.rows() != hssvd_basis_.numObs() || Kstar.cols() != n ||
675 prior_diag.size() != n)
676 return false;
677 const double total_sigma2 = totalPosteriorNoiseVariance();
678 Eigen::VectorXd var_e;
680 var_e = hssvd_basis_.stableRangePosteriorDiagonal(
681 Kstar, prior_diag, prior_diag, total_sigma2,
682 /*check_variance=*/false);
683 } else {
684 Eigen::VectorXd projected =
685 hssvd_basis_.noisyRangeSelfQuadratic(Kstar, total_sigma2);
686 if (projected.size() != n || !projected.allFinite()) return false;
687 var_e = prior_diag - projected;
688 }
689 if (var_e.size() != n || !var_e.allFinite()) return false;
690 Eigen::VectorXd var_full = Eigen::VectorXd::Zero(n * (D + 1));
691 var_full.head(n) = var_e;
692 Eigen::VectorXd energy_noise = Eigen::VectorXd::Zero(n);
693 priorFromKernelDiagonal(R_e, energy_noise);
694 Eigen::VectorXd observation_noise =
695 Eigen::VectorXd::Zero(var_full.size());
696 observation_noise.head(n) = energy_noise;
697 std::vector<char> replaced;
698 if (!applyHssvdTrainingRowLatentVariance(
699 query.R, var_full, total_sigma2, &observation_noise, &replaced))
700 return false;
701 var_e = var_full.head(n);
702 for (Eigen::Index row = 0; row < var_e.size(); ++row) {
704 !replaced[static_cast<std::size_t>(row)])
706 prior_diag(row));
707 if (!std::isfinite(var_e(row)) || !(var_e(row) >= 0.0))
708 return false;
709 }
710 const double s2 = y_scale_ * y_scale_;
711 var_e *= s2 * hssvd_variance_calibration_factor_;
712 energy_variance = var_e.transpose();
713 return energy_variance.size() == n;
714 }
715
716#ifdef GPR_LINALG_KOKKOS
717 if (hasDevicePosterior()) return joint_marginal();
718#endif
719 if (!hasTrainingCholeskyFactor(R_matrix.rows())) return joint_marginal();
720
721#ifdef GPR_LINALG_SCALAPACK
722 // hasTrainingCholeskyFactor accepts EITHER an n-by-n dense L or a
723 // distributed factor owned by this instance, so a distributed factor
724 // reaches here with the dense L still 0-by-0. calculateVariance solves
725 // that case through the distributed path; the energy gate needs the
726 // same, with none of the sibling's dim-major to observation-major
727 // permutation: R_e carries one channel per configuration, so the query
728 // side is already observation-major.
729 //
730 // Order matters. DistributedState::initialize re-initializes the BLACS
731 // grid whenever the requested block size differs from the live one, and
732 // that drops the cached factor. The query side carries one channel per
733 // configuration, so assembling its covariance first would request a
734 // block size of 1 against a training grid tiled by D+1 and destroy the
735 // very factor this solve needs. The projection is taken while the
736 // factor is still live, and the prior diagonal afterwards.
737 if (training_cholesky_is_distributed_) {
738 const EigenMatrix R_train =
740 const Eigen::VectorXd R_train_ind =
742 : R_indices;
743 int desc_kk[9];
744 std::vector<double> KK_dist;
745 assembleCrossCovarianceDistributed(R_train, R_e, R_train_ind, R_e_ind,
746 KK_dist, desc_kk);
747 EigenMatrix prior_matrix;
748 evaluateTrainingCovarianceMatrix(R_e, R_e_ind, prior_matrix,
749 /*serial_per_rank=*/true);
750 if (prior_matrix.rows() != n || prior_matrix.cols() != n) return false;
751 Eigen::VectorXd prior_diag = prior_matrix.diagonal();
752 priorFromTrainingDiagonal(R_e, prior_diag);
753 Eigen::VectorXd var_e;
755 var_e = backend().bordered_cholesky_diagonal_distributed(
756 L, std::move(KK_dist), desc_kk,
757 static_cast<int>(R_train.rows()), static_cast<int>(n),
758 prior_diag);
759 } else {
760 const Eigen::VectorXd projected =
761 backend().forward_solve_mat_colwise_squared_norm_distributed(
762 L, std::move(KK_dist), desc_kk,
763 static_cast<int>(R_train.rows()), static_cast<int>(n));
764 if (projected.size() != n) return false;
765 var_e = prior_diag - projected;
766 }
767 if (var_e.size() != n || !var_e.allFinite()) return false;
768 energy_variance =
769 (y_scale_ * y_scale_ * hssvd_variance_calibration_factor_) *
770 var_e.transpose();
771 return true;
772 }
773#endif
774
775 EigenMatrix cov_matrix;
776 evaluateTrainingCovarianceMatrix(R_e, R_e_ind, cov_matrix,
777 /*serial_per_rank=*/true);
778 if (cov_matrix.rows() != n || cov_matrix.cols() != n) return false;
780 R_e, R_e_ind, /*serial_per_rank=*/true);
781 if (KK.rows() != R_matrix.rows() || KK.cols() != n) return false;
782 Eigen::VectorXd prior_diag = cov_matrix.diagonal();
783 priorFromTrainingDiagonal(R_e, prior_diag);
784 const EigenMatrix kk_eval = rigid_deflation_.isActiveForFullOrder(KK.rows())
785 ? rigid_deflation_.projectRows(KK)
786 : KK;
787 Eigen::VectorXd var_e;
789 var_e = trainingSolver().posteriorVarianceDiagonal(kk_eval, prior_diag);
790 else
791 var_e = prior_diag - trainingSolver().quadraticDiagonal(kk_eval);
792 if (var_e.size() != n || !var_e.allFinite()) return false;
793 energy_variance =
794 (y_scale_ * y_scale_ * hssvd_variance_calibration_factor_) *
795 var_e.transpose();
796 return true;
797}

◆ tryGateEnergyVarianceInterval()

bool gpr::GaussianProcessRegression::tryGateEnergyVarianceInterval ( const Observation & query,
Eigen::RowVectorXd & energy_variance_lower,
Eigen::RowVectorXd & energy_variance_upper )
nodiscard

Two-sided certified Schur energy-variance intervals [lower, upper] from the exact-kernel HS-SVD MAP bordered factor. The noise is the one the trained factor inverts (condition-floored, as for the mean). A negative lower endpoint is clamped to zero when the upper endpoint is nonnegative. Returns false when the model lacks the exact kernel; throws std::domain_error when M cannot be certified positive definite or the upper endpoint is negative.

Definition at line 837 of file Variance.cpp.

840{
841 ScopedVarianceTimer variance_timer;
842 energy_variance_lower.resize(0);
843 energy_variance_upper.resize(0);
844 const Index_t n = query.R.rows();
845 const Index_t D = query.R.cols();
846 if (n <= 0 || D <= 0) return false;
847 if (!canCertifyEnergyVarianceInterval()) return false;
848
849 EigenMatrix R_e = query.R;
850 Eigen::VectorXd R_e_ind = Eigen::VectorXd::Zero(n);
851 EigenMatrix Kstar;
852 Eigen::VectorXd prior_diag;
853 if (assembleHssvdDualCrossCovariance(R_e, Kstar, &prior_diag,
854 /*energy_only=*/true)) {
855 priorFromKernelDiagonal(R_e, prior_diag);
856 } else {
857 evaluateCovarianceMatrix(R_matrix, R_e, R_indices, R_e_ind, Kstar,
858 /*serial_per_rank=*/true);
859 EigenMatrix cov_matrix;
860 evaluateTrainingCovarianceMatrix(R_e, R_e_ind, cov_matrix,
861 /*serial_per_rank=*/true);
862 if (cov_matrix.rows() != n || cov_matrix.cols() != n)
863 throw std::logic_error(
864 "energy variance interval prior assembly failed");
865 prior_diag = cov_matrix.diagonal();
866 priorFromTrainingDiagonal(R_e, prior_diag);
867 }
868 if (Kstar.rows() != hssvd_basis_.numObs() || Kstar.cols() != n ||
869 prior_diag.size() != n)
870 throw std::logic_error(
871 "energy variance interval covariance assembly failed");
872
873 std::vector<BorderedVarianceInterval> intervals;
874 try {
875 intervals = hssvd_basis_.noisyBorderedVarianceIntervals(
876 Kstar, prior_diag, totalPosteriorNoiseVariance());
877 } catch (const std::runtime_error& err) {
878 throw std::domain_error(err.what());
879 }
880 if (static_cast<Index_t>(intervals.size()) != n)
881 throw std::logic_error(
882 "energy variance interval result extent mismatch");
883
884 using Work = gpr::extended::WorkingReal;
886 y_scale_, hssvd_variance_calibration_factor_);
887 if (!scale.valid) return false;
888
889 energy_variance_lower.resize(n);
890 energy_variance_upper.resize(n);
891 for (Index_t i = 0; i < n; ++i) {
892 const auto& iv = intervals[static_cast<std::size_t>(i)];
893 if (!std::isfinite(iv.lower) || !std::isfinite(iv.upper)) return false;
894 const double lo = gpr::extended::scaledLowerBound(iv.lower, scale);
895 const double hi = gpr::extended::scaledUpperBound(iv.upper, scale);
896 if (!(hi >= lo))
897 throw std::logic_error(
898 "energy variance interval endpoints are inconsistent");
899 energy_variance_lower(i) = lo;
900 energy_variance_upper(i) = hi;
901 }
902 return true;
903}
std::conditional_t< nativeLongDoubleIsExtended(), long double, DoubleDouble > WorkingReal
double scaledUpperBound(double value, const VarianceScaleEnclosure< Work > &scale)
double scaledLowerBound(double value, const VarianceScaleEnclosure< Work > &scale)

◆ tryPairLocalDirectionalCovariance()

std::optional< bool > gpr::GaussianProcessRegression::tryPairLocalDirectionalCovariance ( const TrainingKernelGeometry & geom,
const Eigen::VectorXd & indices,
const Eigen::VectorXd & direction,
EigenMatrix & first,
EigenMatrix & second,
int rank = 0,
int ranks = 1 ) const
nodiscard

nullopt selects the per-channel representation. A returned false rejects invalid data; true supplies the owned bare kernel derivatives.

Definition at line 969 of file CovarianceAssembly.cpp.

973{
974 if (!use_pair_local_directional_tiles_ || !use_pair_local_tiles_)
975 return std::nullopt;
976 if (!geom.valid || ranks < 1 || rank < 0 || rank >= ranks) return false;
977 if (!pairLocalCoversGeometry(geom) || sexpat_cov_func == nullptr ||
978 sexpat_cov_func->usesManifoldChart() ||
979 sexpat_cov_func->usesGeodesicHeatKernel())
980 return std::nullopt;
981 const Eigen::Index configurations = geom.pair_local.n_conf;
982 const Eigen::Index tile = geom.pair_local.dof + 1;
983 if (indices.size() != geom.n) return false;
984 for (Eigen::Index channel = 0; channel < tile; ++channel)
985 for (Eigen::Index i = 0; i < configurations; ++i)
986 if (indices(channel * configurations + i) != channel)
987 return std::nullopt;
988 if (std::any_of(geom.blocks.begin(), geom.blocks.end(),
989 [&](const auto& block) {
990 return !trainingBlockGeometryUsable(geom, block);
991 }))
992 return false;
993 const Eigen::VectorXd theta = sexpat_cov_func->combineParameters();
994 const auto weights =
995 pairlocal::weightsFromLogParameters(theta, geom.pair_local.n_pt);
996 if (!weights.valid || direction.size() < theta.size() ||
997 !direction.allFinite())
998 return false;
999 // Weights and the probe direction are read here. The cached geometry
1000 // holds coordinates only; these matrices are not stored.
1001 const Eigen::VectorXd kernel_direction = direction.head(theta.size());
1002 first.setZero(geom.n, geom.n);
1003 second.setZero(geom.n, geom.n);
1004 std::vector<std::pair<Eigen::Index, Eigen::Index>> owned_pairs;
1005 owned_pairs.reserve(static_cast<std::size_t>(configurations) *
1006 static_cast<std::size_t>(configurations + 1) / 2);
1007 std::size_t tile_index = 0;
1008 for (Eigen::Index i = 0; i < configurations; ++i)
1009 for (Eigen::Index j = 0; j <= i; ++j) {
1010 if (tile_index++ % static_cast<std::size_t>(ranks) !=
1011 static_cast<std::size_t>(rank))
1012 continue;
1013 owned_pairs.emplace_back(i, j);
1014 }
1015 // One configuration pair writes a disjoint (D+1)^2 tile. n = 10 has
1016 // 55 pairs, below the fine-grain team threshold, and each pair is the
1017 // whole probe, so the coarse grain is what scales the team.
1018 std::atomic<int> failed{0};
1019 backend().local().forEach(
1020 owned_pairs.size(),
1021 [&](std::size_t task) {
1022 if (failed.load(std::memory_order_relaxed) != 0) return;
1023 const auto [i, j] = owned_pairs[task];
1024 pairlocal::TileEvaluator evaluator(geom.pair_local, weights);
1025 Eigen::MatrixXd block_first, block_second;
1026 evaluator.prepare(i, j);
1027 evaluator.directional(kernel_direction, block_first, block_second);
1028 if (!block_first.allFinite() || !block_second.allFinite()) {
1029 failed.store(1, std::memory_order_relaxed);
1030 return;
1031 }
1032 for (Eigen::Index r = 0; r < tile; ++r)
1033 for (Eigen::Index c = 0; c < tile; ++c) {
1034 const Eigen::Index row = r * configurations + i;
1035 const Eigen::Index column = c * configurations + j;
1036 first(row, column) = block_first(r, c);
1037 second(row, column) = block_second(r, c);
1038 if (i != j) {
1039 first(column, row) = block_first(r, c);
1040 second(column, row) = block_second(r, c);
1041 }
1042 }
1043 },
1045 if (failed.load(std::memory_order_relaxed) != 0) return false;
1046 pair_local_directional_tiles_for_testing_ += owned_pairs.size();
1047 return true;
1048}
Weights weightsFromLogParameters(const Eigen::VectorXd &theta, Eigen::Index n_pt)

◆ unchangedSubsetFitSkipsForTesting()

std::size_t gpr::GaussianProcessRegression::unchangedSubsetFitSkipsForTesting ( ) const
inlinenodiscardnoexcept

Fits skipped because the subset and the theta were unchanged.

Definition at line 2497 of file GaussianProcessRegression.h.

2498 {
2499 return unchanged_subset_fit_skips_;
2500 }

◆ unpermuteTrainingVector()

Eigen::VectorXd gpr::GaussianProcessRegression::unpermuteTrainingVector ( const Eigen::VectorXd & input) const
nodiscardprotected

Inverse of permuteTrainingVector: returns input mapped back to the caller training-row order. Identity when no permutation is active. Used by tests and by mixture-mean predict paths that need posterior alpha in the caller's index space.

Definition at line 624 of file GaussianProcessRegression.cpp.

626{
627 if (!hasTrainingPermutation()) return input;
629}

◆ updateConfiguration()

void gpr::GaussianProcessRegression::updateConfiguration ( const AtomsConfiguration & conf_info)

Update the internal atoms configuration. Use this when the set of active/frozen atoms changes dynamically.

Definition at line 4447 of file Optimize.cpp.

4449{
4450 const bool changed_pair_hierarchy =
4451 atoms_config.n_pt != conf_info.n_pt ||
4452 atoms_config.n_base_pt != conf_info.n_base_pt ||
4453 atoms_config.pair_type_parent != conf_info.pair_type_parent;
4454 const AtomsConfiguration& kernel_conf = sexpat_cov_func != nullptr
4455 ? sexpat_cov_func->getConfInfo()
4456 : atoms_config;
4457 const double far_radius =
4458 sexpat_cov_func != nullptr ? sexpat_cov_func->farFieldRadius() : 0.0;
4459 if (!detail::sameSexpatGeometry(kernel_conf, conf_info, far_radius,
4460 far_radius) ||
4461 (atomic_environment_model_ &&
4462 !sameAtomicEnvironmentGeometry(atoms_config, conf_info))) {
4463 // Pair features determine every posterior representation, including
4464 // parked factors whose dimensions can match a different environment.
4465 invalidateLikelihoodNoiseDependentState();
4466 pending_hyperparameter_posterior_ = {};
4467 serial_factor_signature_.valid = false;
4468 active_posterior_.reset();
4469 full_fit_observations_.clear();
4470 active_kernel_evidence_.clear();
4472 ++factor_epoch_;
4473 }
4474 this->atoms_config = conf_info;
4475 // Geometry updates retain learned releases. A changed chemical typing
4476 // requires the hierarchy that belongs to those pair indices.
4477 if (changed_pair_hierarchy) configureLengthScaleTies(conf_info);
4478 configureZBLPriorMean(conf_info);
4479 configureFFPriorMean(conf_info);
4480
4481 if (sexpat_cov_func != nullptr) {
4482 sexpat_cov_func->setConfInfo(conf_info);
4483 }
4484
4486 ++laplace_model_revision_;
4487 laplace_posterior_.reset();
4488 invalidateObjectiveStationarityHessian();
4489}

◆ updateModelWithFullData()

void gpr::GaussianProcessRegression::updateModelWithFullData ( const Observation & full_observation)

Definition at line 4205 of file Optimize.cpp.

4207{
4208 ScopedPhaseTimer condition_timer(PhaseTimers::condition_seconds);
4209 detail::requireJointTrainingObservation(
4210 full_observation, "GaussianProcessRegression::updateModelWithFullData");
4211 if (atomic_environment_model_) {
4213 fitAtomicEnvironmentModel(full_observation, false);
4214 return;
4215 }
4216 // Automatic selection and its candidate model build run before this
4217 // rebuild mutates the posterior. A refusal throws and leaves the previous
4218 // model in place; a deferral (fewer than two geometries) keeps the exact
4219 // path. Fixed counts do not enter this branch.
4220 int selected_features = rff_features_requested_;
4221 std::optional<RFFModel> staged_auto_rff;
4222 if (rff_auto_) {
4223 const RFFFeatureSelection selection =
4224 selectRFFFeatures(full_observation);
4225 selected_features = selection.accepted ? selection.features : 0;
4226 if (selected_features > 0 && full_observation.E.size() > 0) {
4227 const Eigen::Index n_design =
4228 full_observation.R.rows() * (1 + full_observation.R.cols());
4229 if (n_design < 2 * static_cast<Eigen::Index>(selected_features)) {
4230 RFFFeatureSelection failed = rff_selection_;
4231 failed.accepted = false;
4232 failed.features = 0;
4233 failed.status = "rejected";
4234 failed.detail =
4235 "RFF feature selection refused: the validated count is not "
4236 "twice overdetermined on the full design. No feature count "
4237 "was installed.";
4238 rff_selection_ = failed;
4239 logRFFFeatureSelection(failed);
4240 throw RFFFeatureSelectionError(std::move(failed));
4241 }
4242 try {
4243 double energy_noise = 0.0;
4244 double gradient_noise = 0.0;
4245 const Observation residual = rffStandardizedResidual(
4246 full_observation, energy_noise, gradient_noise);
4247 std::shared_ptr<const linalg::MpiCommunicator> comm;
4248#if defined(GPR_HAVE_MPI) || defined(GPR_LINALG_SCALAPACK)
4249 const auto comm_ctx = mpiContext();
4250 if (comm_ctx.comm != linalg::kMpiCommNull) {
4251 comm = std::make_shared<linalg::MpiCommunicator>(
4252 comm_ctx.comm);
4253 }
4254#endif
4255 RFFModel candidate = comm ? RFFModel(comm) : RFFModel();
4256 candidate.build(*sexpat_cov_func, atoms_config, residual,
4257 selected_features, energy_noise,
4258 gradient_noise);
4259 PhaseTimers::notePeak("rff_build");
4260 staged_auto_rff = std::move(candidate);
4261 } catch (const RFFFeatureSelectionError&) {
4262 throw;
4263 } catch (const std::exception& ex) {
4264 RFFFeatureSelection failed = rff_selection_;
4265 failed.accepted = false;
4266 failed.features = 0;
4267 failed.status = "rejected";
4268 failed.detail = std::string(
4269 "RFF feature selection refused after "
4270 "validation: the chosen model did not "
4271 "build (") +
4272 ex.what() +
4273 "). No feature count was installed.";
4274 rff_selection_ = failed;
4275 logRFFFeatureSelection(failed);
4276 throw RFFFeatureSelectionError(std::move(failed));
4277 }
4278 }
4279 }
4280 active_posterior_.reset();
4281 full_fit_observations_ = full_observation;
4282#ifdef GPR_LINALG_SCALAPACK
4283 parked_training_cholesky_.clear();
4284#endif
4285 ++full_data_rebuilds_for_testing_;
4286 ++factor_epoch_;
4287 aux::AuxiliaryFunctionality aux_func;
4288
4289 if (this->report_level >= 2) {
4290 log_man << "Full-data rebuild: assemble observations n="
4291 << full_observation.R.rows()
4292 << " dim=" << full_observation.R.cols() << ".\n";
4293 }
4294
4295 // Assemble matrices with the full dataset.
4296 aux_func.assembleMatrixOfRepetitiveCoordinates(full_observation.R, R_matrix,
4297 R_indices);
4298 aux_func.assembleVectorFromEnergyAndGradient(full_observation,
4300 subtractPriorMeanFromTargets(full_observation.R, full_observation.E.size(),
4302 if (this->report_level >= 2) {
4303 log_man << "Full-data rebuild: assembled design rows="
4304 << R_matrix.rows() << " cols=" << R_matrix.cols()
4305 << " targets=" << energy_and_gradient.size() << ".\n";
4306 }
4307 standardizeTargets(energy_and_gradient, full_observation.E.size());
4308 if (this->report_level >= 2) {
4309 log_man << "Full-data rebuild: targets standardized scale=" << y_scale_
4310 << " mean=" << y_mean_ << ".\n";
4311 }
4312 ++laplace_model_revision_;
4313 // Do not reset laplace_posterior_ here. The stamp on the cached posterior
4314 // captures the old laplace_model_revision_; ensureLaplacePosterior()
4315 // detects the mismatch and rebuilds on next use. Keeping the old H around
4316 // is required for the Laplace-driven skip-SCG predicate, which uses the
4317 // old H to estimate the Newton-step magnitude under the new data.
4318
4319 // RFF scale cutoff. Above n_design >= 2*D_rff the exact dual-kernel
4320 // eigensolve (O(rank^3) per outer; the rank-6000 hermes_123
4321 // bottleneck) is replaced by the RFF Bayesian linear
4322 // regression (O(N D D_rff + D_rff^3), self-contained on the raw
4323 // targets via its own BLR precision). The RFF model then supplies
4324 // BOTH the predict mean and variance, so the eigensolve is skipped
4325 // entirely. Below the cutoff (small-rank systems) this branch is
4326 // never taken and the exact path below runs bit-identically -- the
4327 // artifact-free guarantee. The 2x-overdetermined guard keeps the BLR
4328 // posterior well-conditioned (matches the layered-RFF gate). RFF
4329 // build failure falls through to the exact decompose.
4330 rff_replaces_exact_ = false;
4331 if (rff_auto_ && selected_features == 0) {
4332 rff_features_ = 0;
4333 rff_standardized_targets_ = false;
4334 }
4335 if (selected_features > 0 && full_observation.E.size() > 0) {
4336 const Eigen::Index n_design =
4337 full_observation.R.rows() * (1 + full_observation.R.cols());
4338 if (n_design >= 2 * static_cast<Eigen::Index>(selected_features)) {
4339 try {
4340 if (rff_auto_) {
4341 rff_model_ = std::move(*staged_auto_rff);
4342 rff_features_ = selected_features;
4343 rff_standardized_targets_ = true;
4344 } else {
4345 buildRFFModel(full_observation, selected_features);
4346 }
4347 C.resize(0, 0);
4349 a.resize(0);
4350 b.resize(0);
4351 descriptor_predictor_ready_ = false;
4352 clearHssvdBasisState();
4353 rff_replaces_exact_ = true;
4355 if (this->report_level >= 2) {
4356 log_man << "Full-data rebuild: RFF replaces exact solve "
4357 "(n_design="
4358 << n_design
4359 << " >= 2*D_rff=" << 2 * selected_features
4360 << ", D_rff=" << selected_features
4361 << "); dual-kernel eigensolve skipped.\n";
4362 }
4363 return;
4364 } catch (const RFFFeatureSelectionError&) {
4365 throw;
4366 } catch (const std::exception& ex) {
4367 rff_replaces_exact_ = false;
4368 rff_features_ = 0;
4369 rff_standardized_targets_ = false;
4370 if (this->report_level >= 1) {
4371 log_man << "RFF replace build failed: " << ex.what()
4372 << "; falling back to exact decompose.\n";
4373 }
4374 }
4375 }
4376 }
4377
4378 // Re-decompose the covariance matrix with new hyperparameters and full data
4379 if (this->report_level >= 2) {
4380 log_man << "Full-data rebuild: covariance decompose start hssvd="
4381 << (use_hssvd_backend_ ? 1 : 0) << ".\n";
4382 }
4383 bool posterior_refreshed = false;
4384 const auto condition_on_rows = [&]() {
4385 posterior_refreshed = false;
4386 if (use_hssvd_backend_) {
4387 posterior_refreshed = refreshFullDataPosteriorHssvd();
4388 is_decomposed_succesfully = posterior_refreshed;
4389 }
4390 if (!posterior_refreshed) {
4393 }
4394 };
4395 condition_on_rows();
4396 // Robust rows: one EM sweep per rebuild. The E-step reads the
4397 // conditioned model's leave-one-geometry-out residuals; the M-step
4398 // is the same conditioning with the reweighted noise.
4399 if (is_decomposed_succesfully && robust_nu_ > 0.0 &&
4400 updateRobustRowWeights(full_observation)) {
4401 condition_on_rows();
4402 }
4403 if (this->report_level >= 2) {
4404 log_man << "Full-data rebuild: covariance decompose status="
4405 << (is_decomposed_succesfully ? 1 : 0)
4406 << " hssvd_valid=" << (hssvd_basis_valid_ ? 1 : 0)
4407 << " hssvd_rank=" << hssvd_basis_.rank() << ".\n";
4408 }
4409
4411 if (report_level >= 1) {
4412 log_man << "Warning! Matrix L is not positive definite after "
4413 "re-evaluation with full dataset.\n";
4414 }
4415 } else if (!posterior_refreshed) {
4416 if (this->report_level >= 2) {
4417 log_man << "Full-data rebuild: posterior refresh start.\n";
4418 }
4419 refreshPosteriorWeights(energy_and_gradient);
4420 if (this->report_level >= 2) {
4421 log_man << "Full-data rebuild: posterior refresh done.\n";
4422 }
4423 }
4424
4425 if (this->report_level >= 2) {
4426 log_man << "Final model updated with " << full_observation.R.rows()
4427 << " data points.\n";
4428 log_man << "magnSigma2: " << sexpat_cov_func->getMagnSigma2() << "\n";
4429 log_man << "lengthScales:\n"
4430 << Eigen::Map<Eigen::VectorXd>(
4431 sexpat_cov_func->getLengthScaleRef().data(),
4432 sexpat_cov_func->getLengthScaleRef().size())
4433 << "\n";
4434 }
4435 if (report_level >= 2 && backend().mpi().rank == 0) {
4436 const auto& ls = sexpat_cov_func->getLengthScaleRef();
4437 std::fprintf(stderr, "[GPR_TRACE_LS] N=%lld magnSigma2=%.6g ls=[",
4438 static_cast<long long>(full_observation.R.rows()),
4439 sexpat_cov_func->getMagnSigma2());
4440 for (Eigen::Index k = 0; k < ls.size(); ++k)
4441 std::fprintf(stderr, "%s%.6g", k ? " " : "", *(ls.data() + k));
4442 std::fprintf(stderr, "] sigma2n=%.6g\n",
4443 lik_gaussian ? lik_gaussian->getSigma2() : -1.0);
4444 }
4445}
RFFFeatureSelection selectRFFFeatures(const Observation &observation, std::uint64_t memory_cap_bytes=kRFFValidationMemoryCapBytes)
bool updateRobustRowWeights(const Observation &full_observation)
static double condition_seconds

◆ updateRobustRowWeights()

bool gpr::GaussianProcessRegression::updateRobustRowWeights ( const Observation & full_observation)

E-step over the conditioned model: leave-one-geometry-out residuals of every training configuration, their squared Mahalanobis norm, and the extra noise the M-step registers with the likelihood. Returns true when any registered noise changed.

Definition at line 37 of file RobustRows.cpp.

39{
40 if (!(robust_nu_ > 0.0) || !lik_gaussian) return false;
41 const Eigen::Index n_geom = full_observation.R.rows();
42 const Eigen::Index dim = full_observation.R.cols();
43 if (n_geom == 0 || R_matrix.rows() == 0 || R_matrix.cols() != dim + 1 ||
44 energy_and_gradient.size() != R_matrix.rows())
45 return false;
46 const Eigen::Index n = R_matrix.rows();
47 // The training covariance in the assembled row order, with the
48 // likelihood noise (the current extra noise included), the constant
49 // block, and the jitter the conditioning uses.
52 /*serial_per_rank=*/true,
53 /*include_constant=*/true);
54 if (K.rows() != n || K.cols() != n || !K.allFinite()) return false;
55 if (jitter_sigma2 > 0.0) K.diagonal().array() += jitter_sigma2;
56 applyKernelNugget(K, n);
57 Eigen::LLT<EigenMatrix> llt(K);
58 if (llt.info() != Eigen::Success) return false;
59 const EigenMatrix& L_dense = llt.matrixLLT();
60 const Eigen::VectorXd alpha = llt.solve(energy_and_gradient);
61 if (!alpha.allFinite()) return false;
62
63 const double sigma2 = lik_gaussian->getSigma2();
64 Eigen::VectorXd z2 = Eigen::VectorXd::Zero(n_geom);
65 Eigen::VectorXd extra = Eigen::VectorXd::Zero(n_geom);
66 Eigen::VectorXd channels = Eigen::VectorXd::Zero(n_geom);
67 std::vector<Eigen::Index> rows;
68 for (Eigen::Index g = 0; g < n_geom; ++g) {
69 rows.clear();
70 for (Eigen::Index i = 0; i < n; ++i) {
71 if ((R_matrix.row(i).head(dim).array() ==
72 full_observation.R.row(g).array())
73 .all())
74 rows.push_back(i);
75 }
76 const Eigen::Index d = static_cast<Eigen::Index>(rows.size());
77 if (d == 0) continue;
78 channels(g) = static_cast<double>(d);
79 // Z = L^-1 E_B, so (K^-1)_BB = Z^T Z.
80 EigenMatrix E = EigenMatrix::Zero(n, d);
81 Eigen::VectorXd alpha_B(d);
82 for (Eigen::Index k = 0; k < d; ++k) {
83 E(rows[static_cast<std::size_t>(k)], k) = 1.0;
84 alpha_B(k) = alpha(rows[static_cast<std::size_t>(k)]);
85 }
86 const EigenMatrix Z =
87 L_dense.template triangularView<Eigen::Lower>().solve(E);
88 const EigenMatrix Kinv_BB = Z.transpose() * Z;
89 Eigen::LLT<EigenMatrix> block(Kinv_BB);
90 if (block.info() != Eigen::Success) continue;
91 const double norm = alpha_B.dot(block.solve(alpha_B));
92 if (!std::isfinite(norm) || norm < 0.0) continue;
93 z2(g) = norm;
94 extra(g) = std::max(0.0, sigma2 * (norm - static_cast<double>(d)) /
95 (robust_nu_ + static_cast<double>(d)));
96 }
97 const Eigen::VectorXd& previous = lik_gaussian->geometryExtraNoise();
98 const bool changed = previous.size() != n_geom ||
99 (previous - extra).cwiseAbs().maxCoeff() >
100 std::numeric_limits<double>::epsilon() *
101 (1.0 + extra.cwiseAbs().maxCoeff());
102 robust_z2_ = z2;
103 robust_extra_ = extra;
104 lik_gaussian->setGeometryExtraNoise(full_observation.R, extra);
105 if (report_level >= 1) {
106 Eigen::Index downweighted = 0;
107 for (Eigen::Index g = 0; g < n_geom; ++g)
108 if (extra(g) > 0.0) ++downweighted;
109 Eigen::Index worst = 0;
110 z2.maxCoeff(&worst);
111 log_man << "Robust rows: nu=" << robust_nu_ << ", " << downweighted
112 << "/" << n_geom
113 << " configurations above their expected "
114 "leave-one-geometry-out misfit; worst z2="
115 << z2(worst) << " over " << channels(worst)
116 << " channels (weight "
117 << (robust_nu_ + channels(worst)) / (robust_nu_ + z2(worst))
118 << ", extra noise " << extra(worst) << ")\n";
119 }
120 return changed;
121}

◆ useLogNormalMagnPrior()

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

Definition at line 1790 of file GaussianProcessRegression.h.

1791 {
1792 return sexpat_cov_func ? sexpat_cov_func->useLogNormalMagnPrior()
1793 : scg_opt_settings.map_use_lognormal_magn_prior;
1794 }

◆ usePrecisionMatrix()

bool gpr::GaussianProcessRegression::usePrecisionMatrix ( ) const
inlinenodiscardnoexcept

Definition at line 4111 of file GaussianProcessRegression.h.

4112 {
4113 return use_precision_;
4114 }

◆ usesFullObservationForHyperparameterOptimization()

bool gpr::GaussianProcessRegression::usesFullObservationForHyperparameterOptimization ( const Observation & observation) const
inlinenodiscardnoexcept

Definition at line 1456 of file GaussianProcessRegression.h.

1458 {
1459 return observation.R.rows() <= fps_options.history;
1460 }

◆ varianceConvention()

VarianceConvention gpr::GaussianProcessRegression::varianceConvention ( ) const
inlinenodiscardnoexcept

Definition at line 3010 of file GaussianProcessRegression.h.

3011 {
3012 return variance_convention_;
3013 }

◆ varianceSolveCacheHitsForTesting()

std::size_t gpr::GaussianProcessRegression::varianceSolveCacheHitsForTesting ( ) const
inlinenodiscardnoexcept

Definition at line 3173 of file GaussianProcessRegression.h.

3174 {
3175 return variance_solve_cache_hits_for_testing_;
3176 }

◆ varianceSubsetConfigurationIds()

const std::vector< int > & gpr::GaussianProcessRegression::varianceSubsetConfigurationIds ( ) const
inlinenodiscardnoexcept

Definition at line 2280 of file GaussianProcessRegression.h.

2282 {
2283 return variance_subset_forced_ids_;
2284 }

◆ varianceSubsetFactorizationsForTesting()

std::size_t gpr::GaussianProcessRegression::varianceSubsetFactorizationsForTesting ( ) const
inlinenodiscardnoexcept

Definition at line 2289 of file GaussianProcessRegression.h.

2291 {
2292 return variance_subset_factorizations_;
2293 }

◆ varianceSubsetFootprint()

bool gpr::GaussianProcessRegression::varianceSubsetFootprint ( ) const
inlinenodiscardnoexcept

Definition at line 2270 of file GaussianProcessRegression.h.

2271 {
2272 return variance_subset_footprint_;
2273 }

◆ varianceSubsetQueriesForTesting()

std::size_t gpr::GaussianProcessRegression::varianceSubsetQueriesForTesting ( ) const
inlinenodiscardnoexcept

Definition at line 2285 of file GaussianProcessRegression.h.

2286 {
2287 return variance_subset_queries_;
2288 }

◆ wallClockLimitReached()

bool gpr::GaussianProcessRegression::wallClockLimitReached ( ) const
inlinenodiscard

Collective on the model's process group for distributed fitters.

Definition at line 2544 of file GaussianProcessRegression.h.

2545 {
2546 return optimizationDeadlineReached(wall_clock_limit_, backend_context_);
2547 }

◆ consumerPublicLayout

PublicLayoutBytes consumerPublicLayout ( )
friend

◆ detail::TiedLengthScaleObjective

template<class Inner>
friend struct detail::TiedLengthScaleObjective
friend

Definition at line 4491 of file GaussianProcessRegression.h.

◆ libraryPublicLayout

PublicLayoutBytes libraryPublicLayout ( )
friend

Definition at line 15 of file PublicLayout.cpp.

16{
17 PublicLayoutBytes out;
18 out.gaussian_process = sizeof(GaussianProcessRegression);
19 out.gaussian_process_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}

◆ tests::GaussianProcessRegressionTest

friend class tests::GaussianProcessRegressionTest
friend

Definition at line 3639 of file GaussianProcessRegression.h.

Member Data Documentation

◆ a

Eigen::VectorXd gpr::GaussianProcessRegression::a
mutableprotected

Definition at line 5467 of file GaussianProcessRegression.h.

◆ b

Eigen::VectorXd gpr::GaussianProcessRegression::b
protected

Definition at line 5466 of file GaussianProcessRegression.h.

◆ C

EigenMatrix gpr::GaussianProcessRegression::C
protected

Definition at line 5463 of file GaussianProcessRegression.h.

◆ dense_results_

linalg::linop::DenseResultCache gpr::GaussianProcessRegression::dense_results_
mutableprotected

Definition at line 5418 of file GaussianProcessRegression.h.

◆ device_posterior_

std::shared_ptr<linalg::KokkosMolecularPosterior> gpr::GaussianProcessRegression::device_posterior_
protected

Definition at line 5422 of file GaussianProcessRegression.h.

◆ device_targets_placeholder_

bool gpr::GaussianProcessRegression::device_targets_placeholder_ = false
protected

Definition at line 5423 of file GaussianProcessRegression.h.

◆ energy_and_gradient

Eigen::VectorXd gpr::GaussianProcessRegression::energy_and_gradient
protected

Definition at line 5474 of file GaussianProcessRegression.h.

◆ flip_threshold_

const double gpr::GaussianProcessRegression::flip_threshold_ = 0.8
protected

Definition at line 5483 of file GaussianProcessRegression.h.

◆ has_training_permutation_

bool gpr::GaussianProcessRegression::has_training_permutation_ = false
protected

Definition at line 5472 of file GaussianProcessRegression.h.

◆ history_increment_

const int gpr::GaussianProcessRegression::history_increment_ = 2
protected

Definition at line 5485 of file GaussianProcessRegression.h.

◆ hyperparameter_history_

std::deque<Eigen::VectorXd> gpr::GaussianProcessRegression::hyperparameter_history_
protected

Definition at line 5476 of file GaussianProcessRegression.h.

◆ is_decomposed_succesfully

bool gpr::GaussianProcessRegression::is_decomposed_succesfully
protected

Definition at line 5299 of file GaussianProcessRegression.h.

◆ is_training_cov_matrix_evaluated

bool gpr::GaussianProcessRegression::is_training_cov_matrix_evaluated
protected

Definition at line 5298 of file GaussianProcessRegression.h.

◆ krylov_objective_

KrylovObjectiveState gpr::GaussianProcessRegression::krylov_objective_
protected

Definition at line 5443 of file GaussianProcessRegression.h.

◆ L

EigenMatrix gpr::GaussianProcessRegression::L
mutableprotected

Definition at line 5465 of file GaussianProcessRegression.h.

◆ max_history_

const int gpr::GaussianProcessRegression::max_history_ = 30
protected

Definition at line 5487 of file GaussianProcessRegression.h.

◆ monitoring_window_

const int gpr::GaussianProcessRegression::monitoring_window_ = 5
protected

Definition at line 5481 of file GaussianProcessRegression.h.

◆ objective_backend_override_

ObjectiveBackend gpr::GaussianProcessRegression::objective_backend_override_ = ObjectiveBackend::Dense
protected

Definition at line 5444 of file GaussianProcessRegression.h.

◆ optimization_required_positions_

Coord gpr::GaussianProcessRegression::optimization_required_positions_
protected

Definition at line 5489 of file GaussianProcessRegression.h.

◆ optimization_row_pool_

std::vector<bool> gpr::GaussianProcessRegression::optimization_row_pool_
protected

Definition at line 5488 of file GaussianProcessRegression.h.

◆ R_indices

Eigen::VectorXd gpr::GaussianProcessRegression::R_indices
protected

Definition at line 5469 of file GaussianProcessRegression.h.

◆ R_matrix

EigenMatrix gpr::GaussianProcessRegression::R_matrix
protected

Definition at line 5468 of file GaussianProcessRegression.h.

◆ resident_training_factor_

std::shared_ptr<const linalg::KokkosFactor> gpr::GaussianProcessRegression::resident_training_factor_
protected

Definition at line 5421 of file GaussianProcessRegression.h.

◆ rigid_deflation_

detail::RigidDeflationState gpr::GaussianProcessRegression::rigid_deflation_
protected

Definition at line 5588 of file GaussianProcessRegression.h.

◆ rigid_deflation_diag_

RigidDeflationDiagnostic gpr::GaussianProcessRegression::rigid_deflation_diag_
protected

Definition at line 5589 of file GaussianProcessRegression.h.

◆ serial_factor_rigid_deflation_enabled_

bool gpr::GaussianProcessRegression::serial_factor_rigid_deflation_enabled_ = false
protected

Definition at line 5587 of file GaussianProcessRegression.h.

◆ sexpat_cov_func

std::unique_ptr<SexpatCF> gpr::GaussianProcessRegression::sexpat_cov_func

Definition at line 4092 of file GaussianProcessRegression.h.

◆ training_inverse_diagonal_

Eigen::VectorXd gpr::GaussianProcessRegression::training_inverse_diagonal_
mutableprotected

Lazily materialized inverse diagonal in factor order, invalidated by every full rebuild. The unit-calibration bound needs only diag(L).

Definition at line 5563 of file GaussianProcessRegression.h.

◆ training_permutation_

StructuredPermutation gpr::GaussianProcessRegression::training_permutation_
protected

Definition at line 5471 of file GaussianProcessRegression.h.

◆ use_hod

const bool gpr::GaussianProcessRegression::use_hod = true
protected

Definition at line 5479 of file GaussianProcessRegression.h.

◆ use_precision_

bool gpr::GaussianProcessRegression::use_precision_ = false
protected

Definition at line 5417 of file GaussianProcessRegression.h.

◆ use_rigid_null_deflation_

bool gpr::GaussianProcessRegression::use_rigid_null_deflation_ = false
protected

Definition at line 5586 of file GaussianProcessRegression.h.


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