class gpr::GaussianProcessRegression¶
Overview¶
#include <gpr/ml/GaussianProcessRegression.h>
class GaussianProcessRegression {
public:
// typedefs
typedef std::function<bool(const Eigen::VectorXd&, Eigen::VectorXd&)> MeanHessianAction;
typedef std::function<MeanHessianAction(const Eigen::VectorXd&)> MeanHessianPreparation;
// enums
enum LikelihoodNoiseVarianceUpdate;
enum MeanHessianProductStatus;
enum MeasuredRowVerdict;
enum MixtureMeanHessianStatus;
enum ObjectiveBackend;
enum VarianceConvention;
// structs
struct ActiveKernelEvidence;
struct ActivePosteriorState;
struct AnnealStageSummary;
struct AtomicEnvironmentParameterState;
struct BaseKernelExecutionConfig;
struct CachedVarianceSolve;
struct ConvergedSubsetFit;
struct FittedHyperparameterDensity;
struct ForceCalibrationReport;
struct HssvdDualLocalModel;
struct KrylovObjectiveState;
struct LaplacePosteriorFactor;
struct LaplacePosteriorSignature;
struct LaplacePosteriorStamp;
struct LaplacePosteriorState;
struct LaplaceTrainingCovarianceGeometry;
struct LeaveOneOutCalibrationReport;
struct LengthScaleFitState;
struct LengthScaleTies;
struct MarginalLikelihoodReport;
struct ObjectivePlan;
struct OptimizationObjectiveFrame;
struct OptimizerState;
struct PreparedHssvdHessianVector;
struct ProfileSplitTotals;
struct ScgStallScope;
struct SecantQuadraticPriorState;
struct SerialFactorSignature;
struct SliceLaplaceState;
struct farthest_point_sampling_t;
// classes
class ActivePosteriorRestorePoint;
class HyperparameterPosterior;
class RefitTrustReport;
// fields
std::unique_ptr<SexpatCF> sexpat_cov_func;
// construction
GaussianProcessRegression();
GaussianProcessRegression(std::shared_ptr<const linalg::MpiCommunicator> communication);
virtual ~GaussianProcessRegression();
// methods
linalg::MpiContext mpiContext() const;
Eigen::VectorXd solveTrainingCovarianceInFactorLayout(const Eigen::VectorXd& rhs) const;
void initialize(const InputParameters& parameters, const AtomsConfiguration& conf_info);
bool initialized() const;
void setConditionedHessian(const Eigen::VectorXd& point, const Eigen::MatrixXd& hessian);
void clearConditionedHessians();
bool findConditionedHessian(const Eigen::VectorXd& point, Eigen::MatrixXd& hessian_out) const;
void setModelProfile(GPModelProfile profile);
GPModelProfile getModelProfile() const;
void setAtomicEnvironmentModel(bool enabled);
bool atomicEnvironmentModelEnabled() const;
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);
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();
void setOptimizationRowPool(std::vector<bool> pool);
void clearOptimizationRowPool();
std::vector<std::size_t> holdLengthScalesUnresolvedBySubset(const Observation& subset);
void setOptimizationRequiredRows(Coord positions);
void clearOptimizationRequiredRows();
void clearModeRefitHint();
void setActivePosteriorRefits(bool enabled);
bool activePosteriorRefitsEnabled() const;
void setEnvironmentResiduals(bool enabled);
bool environmentResidualsEnabled() const;
void setAdditivePairResiduals(bool enabled);
bool additivePairResidualsEnabled() const;
const std::vector<ActiveKernelEvidence>& activeKernelEvidence() const;
double activeFitStartForTesting() const;
Eigen::Index activeFitAnchorCountForTesting() const;
Eigen::Index activeFitSupportCountForTesting() const;
Eigen::Index residualInducingCount() const;
Eigen::Index residualConfigurationCount() const;
bool hasPendingActivePosteriorRefit() const;
bool hasPendingResidualModelRefit() const;
void setUpDefault();
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);
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;
std::size_t fitGeometryBuildsForTesting() 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 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;
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;
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;
double lastStationarityShift() const;
double lastStationarityThreshold() const;
int lastStationarityModel() const;
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;
void extractUniqueIndices(const Eigen::VectorXd& input_ind, Eigen::VectorXd& output_ind) const;
void evaluateEnergyAndGradient(const Eigen::VectorXd& w, const EigenMatrix& x, const Eigen::VectorXd& x_ind, const Eigen::VectorXd& y, EnergyAndGradient& energy_and_gradient);
void optimize(const Observation& observation);
MarginalLikelihoodReport optimizeMarginalLikelihood(const Observation& observation);
bool appendFixedHyperparameters(const Observation& full_observation);
Eigen::Index fullFitObservationCount() const;
Eigen::Index fullFitCoordinateCount() const;
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);
LikelihoodNoiseVarianceUpdate setLikelihoodNoiseVariance(double physical_sigma2, const Observation& full_observation);
bool applyLikelihoodNoiseVarianceFloor(double floor_sigma2, const Observation& full_observation);
void evaluatePriorMeanTargets(const Eigen::VectorXd& positions, double& energy, Eigen::VectorXd& gradient) const;
void optimizeFactorized(const Observation& observation);
void optimizeChemistryFactorized(const Observation& observation);
bool observationBandInfluence(const Observation& observation, const Coord& band_positions, Eigen::VectorXd& influence, bool collective = false);
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);
void setPhysicsCollocationPath(const Coord& path_points);
bool getChemFactorizedHyperparameters() const;
void calculatePotential(Observation& image1);
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);
bool calculateMeanHessian(const Coord& R, Eigen::MatrixXd& hessian);
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);
void calculatePotentialLaplaceSlice(Observation& image1);
void calculateVarianceLaplaceSlice(Observation& image1);
void setUncertaintyMode(UncertaintyMode mode);
UncertaintyMode getUncertaintyMode() const;
HyperparameterPosterior retainHyperparameterPosterior();
HyperparameterPosterior currentHyperparameterPosterior() const;
bool conditionOnHyperparameterPosterior(const HyperparameterPosterior& posterior);
void setUseAlphaKPredictMean(bool use);
bool getUseAlphaKPredictMean() const;
void setUseAlphaKLaplaceMean(bool use);
bool getUseAlphaKLaplaceMean() const;
void setLaplaceSkipScgThreshold(double threshold);
double getLaplaceSkipScgThreshold() const;
void setObjectiveStationaritySkipThreshold(double threshold);
double getObjectiveStationaritySkipThreshold() const;
void setObjectiveStationaritySkipAuto(bool use);
void setFitStepStop(bool use);
bool getObjectiveStationaritySkipAuto() const;
bool objectiveStationaritySkipMayBeActive() const;
bool usesFullObservationForHyperparameterOptimization(const Observation& observation) const;
double objectiveStationaritySkipThresholdForTesting(const Eigen::VectorXd& theta_reference) const;
bool hasObjectiveStationarityHessianForTesting() const;
bool hasObjectiveStationarityInverseHessianForTesting() const;
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);
bool getUseTrainingGeometryHandle() const;
void setProfilePredictMean(bool enabled);
bool getProfilePredictMean() const;
void setProfileEnergySplit(bool enabled);
bool getProfileEnergySplit() const;
void setProfileGradientSplit(bool enabled);
bool getProfileGradientSplit() const;
const ProfileSplitTotals& profileSplitTotals() const;
void resetProfileSplitTotals();
void logProfileSplitSummary();
void setHutchinsonProbes(int num_probes);
int getHutchinsonProbes() const;
void setHssvdBackend(bool enabled);
bool getHssvdBackend() const;
void setRigidNullDeflation(bool enabled);
bool rigidNullDeflationEnabled() const;
const RigidDeflationDiagnostic& rigidDeflationDiagnostic() const;
bool hasReusableHssvdPosterior() const;
void setHssvdObjectiveContractions(bool enabled);
bool getHssvdObjectiveContractions() const;
void setHssvdDualChopTolerance(double tol);
double getHssvdDualChopTolerance() const;
void setHssvdDualRandomizedSketch(int sketch_size);
int getHssvdDualRandomizedSketch() const;
void setHssvdDualLapackRrr(bool enabled);
bool getHssvdDualLapackRrr() const;
void setHssvdLocalActiveSetSize(int size);
int getHssvdLocalActiveSetSize() const;
void setHssvdLocalPosteriorActiveSetSize(int size);
int getHssvdLocalPosteriorActiveSetSize() const;
void setMapMeanKernelForTesting(std::shared_ptr<const KernelOperator> kernel);
void setMapMeanKernelOverridesHssvdForTesting(bool override);
bool installActivePosteriorHessianActionsForTesting(MeanHessianPreparation background, bool background_exact, MeanHessianPreparation residual, bool residual_exact);
void resetHssvdHessianVectorCallsForTesting() const;
void setHssvdHessianBlockApplyFailsForTesting(bool fail) const;
std::size_t getHssvdHessianVectorCallsForTesting() const;
void resetDispatchedMapMeanHessianActionsForTesting() const;
std::size_t getDispatchedMapMeanHessianActionsForTesting() const;
void setDisableOutputNormalization(bool d);
void setPriorMeanStatistic(PriorMeanStatistic statistic);
PriorMeanStatistic priorMeanStatistic() const;
bool getDisableOutputNormalization() const;
void setOutputScaleFloor(bool enabled);
bool outputScaleFloor() const;
void synchronizeOutputTransformFrom(const GaussianProcessRegression& source);
void restoreOutputTransform(double mean, double scale, bool frozen_mean);
double outputMean() const;
double outputScale() const;
bool outputMeanFrozen() const;
void setPopulationPrior(priors::PopulationPrior prior);
const priors::PopulationPrior& populationPrior() const;
void applyPopulationPrior(const AtomsConfiguration& conf_info, const Eigen::VectorXd& ls_k, double own_s2_log);
void setUseLsPrior(bool use);
bool getUseLsPrior() const;
void setUseLogNormalMagnPrior(bool use);
bool useLogNormalMagnPrior() const;
void setLengthScaleSeedChemicalFloor(bool enabled);
bool getLengthScaleSeedChemicalFloor() const;
void setRobustNu(double nu);
double robustNu() const;
bool updateRobustRowWeights(const Observation& full_observation);
const Eigen::VectorXd& robustResidualNormsForTesting() const;
const Eigen::VectorXd& robustExtraNoiseForTesting() const;
LengthScaleFitState lengthScaleFitState() const;
void restoreLengthScaleFitState(const LengthScaleFitState& state);
void configureLengthScaleTies(const AtomsConfiguration& configuration);
const LengthScaleTies& lengthScaleTies() const;
void setLengthScaleTies(bool enabled);
void releaseLengthScaleTieForTesting(Index_t member);
int lastTieScreenProbes() const;
bool lastTieScreenUsedHessianVector() const;
const std::vector<double>& lastTieScreenCurvatures() const;
bool lengthScaleTiesActive(Eigen::Index length_count) const;
void tieLengthScaleParameters(Eigen::VectorXd& theta) const;
void poolDescriptorScaleByTies(Eigen::VectorXd& scales) const;
void reduceTiedLengthScaleGradient(Eigen::VectorXd& gradient) const;
void refreshLengthScaleLeaders();
void setPairLocalTiles(bool enabled);
bool pairLocalTilesEnabled() const;
void setPairLocalDirectionalTiles(bool enabled);
void setPrincipledNugget(bool use);
bool getPrincipledNugget() const;
void setKappaMax(double kappa_max);
double getKappaMax() const;
void setUseZBLPriorMean(bool use);
bool getUseZBLPriorMean() const;
void setUseFFPriorMean(bool use);
void setSecantQuadraticPrior(const Eigen::VectorXd& position, const Eigen::VectorXd& gradient, const Eigen::MatrixXd& hessian, double reference_energy);
void clearSecantQuadraticPrior();
SecantQuadraticPriorState retainSecantQuadraticPrior() const;
void restoreSecantQuadraticPrior(const SecantQuadraticPriorState& state);
bool physicalPriorMeanActive() const;
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;
int secantQuadraticPriorUses() const;
bool secantQuadraticPriorActive() const;
bool getUseFFPriorMean() const;
void setLogTrainingGeometry(bool enabled);
bool getLogTrainingGeometry() const;
void setLogRankBlockCholesky(bool enabled);
bool getLogRankBlockCholesky() const;
void setScalapackBlockSize(int block_size);
int getScalapackBlockSize() const;
void setScalapackNprow(int nprow);
int getScalapackNprow() const;
void setCutlassPluginPath(std::string path);
const std::string& getCutlassPluginPath() const;
void setUsePsisLaplace(bool use);
bool getUsePsisLaplace() const;
void setUsePsisDeterministicGrid(bool use);
bool getUsePsisDeterministicGrid() const;
void setUseDeltaMethod(bool use);
bool getUseDeltaMethod() const;
void setDeltaUHMinDiag(double v);
double getDeltaUHMinDiag() const;
void setDeltaMaxRatio(double v);
double getDeltaMaxRatio() const;
void buildRFFModel(const Observation& training_data, int D_rff);
void calculatePotentialRFF(Observation& image);
void calculateVarianceRFF(Observation& image);
int getRFFFeatures() const;
bool isRFFBuilt() const;
void setRFFFeaturesRequested(int D_rff);
int getRFFFeaturesRequested() const;
void enableRFFFeatureSelection(double force_tol_fraction = 0.0);
bool rffFeatureSelectionAuto() const;
double rffForceTolFraction() const;
RFFFeatureSelection selectRFFFeatures(const Observation& observation, std::uint64_t memory_cap_bytes = kRFFValidationMemoryCapBytes);
const RFFFeatureSelection& rffFeatureSelection() const;
void setHyperparameterOptimizationMode(HyperparameterOptimizationMode mode);
void setRgminMethod(rgmin_method_t m);
void setVarianceSubsetConfigurations(int configurations);
void setVarianceSubsetFootprint(bool enabled);
bool varianceSubsetFootprint() const;
void setVarianceSubsetConfigurationIds(std::vector<int> ids);
const std::vector<int>& varianceSubsetConfigurationIds() const;
std::size_t varianceSubsetQueriesForTesting() const;
std::size_t varianceSubsetFactorizationsForTesting() const;
void setAnnealStage(bool enabled, std::size_t budget, std::size_t replicas, std::size_t every, std::uint64_t seed);
void noteSurrogateContradiction();
const AnnealStageSummary& lastAnnealStage() const;
std::size_t lastFitEvaluationsForTesting() const;
std::size_t rgminWarmStartsForTesting() const;
std::size_t rgminWarmPairsForTesting() const;
void setRgminWarmStart(bool keep);
void forgetRgminSessions();
HyperparameterOptimizationMode getHyperparameterOptimizationMode() const;
const char* getHyperparameterOptimizerBackend() const;
void setHyperparameterObjectiveMode(HyperparameterObjectiveMode mode);
HyperparameterObjectiveMode getHyperparameterObjectiveMode() const;
virtual bool exactNlmlHessianVectorAvailable() const;
bool nlmlHessianVectorCurvatureRequested() const;
int nlmlHessianVectorFallbacks() const;
void noteNlmlHessianVectorFallback(const char* where, const char* why);
void setOptimizationSubsetHistory(int rows);
int getOptimizationSubsetHistory() const;
void setSubsetFailureEscalation(bool enabled);
bool subsetFailureEscalation() const;
void setRgminInitialLogMove(double distance);
double rgminInitialLogMove() const;
void setRgminInitialLogMoveWholeSession(bool whole_session);
void setSkipUnchangedSubsetFit(bool enabled);
bool skipUnchangedSubsetFit() const;
std::size_t unchangedSubsetFitSkipsForTesting() const;
std::size_t lastFitConfigurationsForTesting() const;
bool lastWarmStartInfeasible() const;
Eigen::VectorXd fittedKernelParameters() const;
void setHyperparameterActiveMaskForTesting(const std::vector<bool>& mask);
void setScgMaxIterationsForTesting(Index_t max_iter);
void setWallClockLimit(std::shared_ptr<const WallClockLimit> limit);
bool wallClockLimitReached() const;
void setResidualDiagonalCorrectionForTesting(bool use, double eps);
void setNlmlHessianVectorFailureForTesting(bool fail);
void setScgDampingLimitForTesting(double limit);
void setFitTolerancesForTesting(double objective, double step);
void setObjectiveBackend(ObjectiveBackend backend, Eigen::Index rank = 0);
void setObjectiveBackendForTesting(ObjectiveBackend backend, Eigen::Index rank = 0);
ObjectiveBackend lastObjectiveBackend() const;
ObjectivePlan objectivePlan() const;
const linalg::linop::DenseResultCache& denseResultsForTesting() const;
std::size_t gradientReplicatedInverseEntriesForTesting() const;
double fitStepTolerance() const;
bool lastScgFallbackUsedForTesting() const;
bool scgStalledForTesting() const;
void setRequireScgFallbackImprovement(bool enabled);
bool requiresScgFallbackImprovement() const;
bool lastScgHitIterationBudgetForTesting() const;
int lastFitIterations() const;
int lastFitRestarts() const;
const char* lastFitStopReason() const;
void resetLaplacePosteriorSignatureBuildsForTesting() const;
std::size_t laplacePosteriorSignatureBuildsForTesting() const;
bool scaleLaplaceFactorForTesting(std::size_t index, double scale);
void setForceFactorOwnerLaplaceMeanForTesting(bool value);
bool disableLaplaceFactorsForTesting();
void resetLaplaceMeanBlockPartitionCallsForTesting() const;
std::size_t laplaceMeanBlockPartitionCallsForTesting() const;
void resetIncrementalCholeskyCountersForTesting() const;
void invalidateTrainingFactorCache();
std::size_t incrementalCholeskyUpdatesForTesting() const;
std::size_t fullCholeskyFactorizationsForTesting() const;
std::size_t serialFactorReusesForTesting() const;
bool devicePosteriorLiveForTesting() const;
bool residentTrainingFactorRetainedForTesting() const;
bool devicePosteriorCapableForTesting() const;
EigenMatrix trainingCovarianceForTesting() const;
std::size_t activeEnergyVarianceSolvesForTesting() const;
std::size_t inverseDiagonalAppendsForTesting() const;
std::size_t bandInfluenceFactorReusesForTesting() const;
Eigen::VectorXd trainingInverseDiagonalForTesting() const;
std::size_t inverseDiagonalBuildsForTesting() const;
void resetHssvdAppendCountersForTesting() const;
std::size_t hssvdAppendUpdatesForTesting() const;
void resetHssvdFactorizationCountersForTesting() const;
std::size_t hssvdFullFactorizationsForTesting() const;
void resetFullDataRebuildCountersForTesting() const;
std::size_t fullDataRebuildsForTesting() const;
Eigen::Index hssvdBasisObservationCountForTesting() const;
const StableBasisND& hssvdBasisForTesting() const;
bool hssvdEnergyDesign(const FieldMatrixd& query, Eigen::VectorXd& design, Eigen::VectorXd& coeff) const;
double hssvdBasisConditionNumberForTesting() const;
double hssvdVarianceCalibrationFactorForTesting() const;
void setHssvdVarianceCalibrationFactorForTesting(double factor);
void setOutputScaleForTesting(double scale);
void scaleTrainingVarianceToPhysical(Eigen::Ref<Eigen::VectorXd> variance) const;
double totalPosteriorNoiseVarianceForTesting() const;
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;
bool hssvdObjectiveBasisValidForTesting() const;
bool hssvdObjectiveTraceBasisMaterializedForTesting() const;
Eigen::Index hssvdObjectivePendingReplicatedEntriesForTesting() const;
double hssvdObjectiveConditionNumberForTesting() const;
Eigen::Index hssvdObjectiveRankForTesting() const;
double hssvdObjectiveTraceInvNoiseForTesting() const;
const StructuredPermutation& trainingPermutationForTesting() const;
bool hssvdObjectiveUsesDirectInverseForTesting() const;
bool hssvdObjectiveTraceViaCholeskyForTesting() const;
void resetLeaveOneOutObjectiveEvaluationsForTesting() const;
std::size_t leaveOneOutObjectiveEvaluationsForTesting() const;
void resetLocalLooObjectiveEvaluationsForTesting() const;
std::size_t localLooObjectiveEvaluationsForTesting() const;
Eigen::Index hssvdDualForceWeightRowsForTesting() const;
Eigen::Index hssvdDualForceWeightColsForTesting() const;
bool hssvdDualAlphaKPreparedForTesting() const;
void resetDistributedHssvdDualKernelAssemblyCallsForTesting() const;
std::size_t distributedHssvdDualKernelAssemblyCallsForTesting() const;
void resetDistributedHssvdDualKernelFactorizationCallsForTesting() const;
std::size_t distributedHssvdDualKernelFactorizationCallsForTesting() const;
void setDescriptorPredictor(bool enabled);
void setVarianceConvention(VarianceConvention convention);
VarianceConvention varianceConvention() const;
const char* hyperparameterOptimizationModeName() const;
std::size_t lastInlaIterations() const;
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;
bool assembleHssvdDualFullCrossCovarianceForTesting(const EigenMatrix& positions, EigenMatrix& Kstar) const;
bool denseVariancePanelForTesting(const EigenMatrix& positions, EigenMatrix& whitened, Eigen::VectorXd& prior) const;
bool assembleHssvdDualCrossCovarianceForTesting(const EigenMatrix& positions, EigenMatrix& Kstar, Eigen::VectorXd& prior_diag, bool energy_only) const;
bool assembleHssvdDualTrainingKernelForTesting(EigenMatrix& kernel) const;
Eigen::Index hssvdLastLocalActiveSetConfigCountForTesting() const;
Eigen::Index hssvdLastLocalActiveSetObservationCountForTesting() const;
double hssvdLastLocalActiveSetConditionNumberForTesting() const;
Eigen::Index hssvdLastLocalPosteriorConfigCountForTesting() const;
Eigen::Index hssvdLastLocalPosteriorObservationCountForTesting() const;
double hssvdLastLocalPosteriorConditionNumberForTesting() const;
void resetDistributedTrainingCovarianceAssemblyCallsForTesting() const;
std::size_t distributedTrainingCovarianceAssemblyCallsForTesting() const;
void calculatePotentialDispatched(Observation& image1);
void calculatePotentialBatch(std::vector<Observation*> queries);
void calculateVarianceBatch(std::vector<Observation*> queries);
std::uint64_t factorEpoch() const;
std::size_t varianceSolveCacheHitsForTesting() const;
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;
Eigen::Index activePosteriorObservationCount() const;
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;
bool hasBeenOptimized() const;
void setJitterSigma2(double value);
double getJitterSigma2() const;
void setChainImageCount(int n);
void setLengthscaleFloor(double floor);
double getLengthscaleFloor() const;
void setParameters(const GPRSetup& parameters);
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;
double getPhysicalTotalDiagonalRegularization() const;
double likelihoodNoiseVariance() const;
ConstantCF& getConstantCovarianceFunction();
const ConstantCF& getConstantCovarianceFunction() const;
Index_t getNumberOfPotentialCalls() const;
const EigenMatrix& getL() const;
bool hasTrainingCholeskyFactor(Eigen::Index expected_rows) const;
bool parkTrainingCholeskyFactor();
bool activateMaterializedPosterior();
void claimActiveTrainingCholeskyFactor();
const Eigen::VectorXd& getAlpha() const;
const EigenMatrix& getRMatrix() const;
const Eigen::VectorXd& getRIndices() const;
bool hasTrainingPermutation() const;
EigenMatrix rowsInTrainingFactorLayout(const EigenMatrix& input) const;
EigenMatrix symmetricMatrixInTrainingFactorLayout(const EigenMatrix& input) const;
void setParameters(const Eigen::VectorXd& w);
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;
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;
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;
std::size_t nonfiniteMarginalLikelihoodRejections() const;
bool isDecomposedSuccessfully() const;
const Observation& fittedObservations() const;
void extractCoordinatesByIndex(const EigenMatrix& x, const Eigen::VectorXd& ind_Ddim, const Index_t ind, FieldMatrixd& x_loc) const;
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;
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);
double traceInverseProduct(const EigenMatrix& factor, const EigenMatrix& observation_order, const detail::RigidDeflationState* deflation_override = nullptr) const;
void removeColumn(const Index_t column_ind, EigenMatrix& matrix);
Index_t getNumberOfRepetitiveIndices(const Eigen::VectorXd& ind_Ddim) const;
virtual void calculateVariance(Observation& image1);
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&);
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);
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);
bool assembleExactHessian(const Eigen::VectorXd& x_ind, const EigenMatrix& x, const Eigen::VectorXd& y, int n_hyperparameters, Eigen::MatrixXd& H);
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);
bool retainsFittedHyperparameterDensity() const;
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);
void setUsePrecisionMatrix(bool use);
bool usePrecisionMatrix() const;
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);
const laplace::SteinVariationalConfig& getSVGDConfig() const;
};
Detailed Documentation¶
Methods¶
Eigen::VectorXd solveTrainingCovarianceInFactorLayout(const Eigen::VectorXd& rhs) const
Solve the training covariance with RHS and result in factor order. Callers supplying derivative matrices use symmetricMatrixInTrainingFactorLayout.
void initialize(const InputParameters& parameters, const AtomsConfiguration& conf_info)
Initialize GPR class.
Parameters:
conf_info |
Information about the configurations necessary for the GPR model |
parameters |
Structure of parameters |
void 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.
void 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.
void restoreAtomicEnvironmentParameterState(const AtomicEnvironmentParameterState& state)
Restore the atomic parameter domain and invalidate its conditioning. The caller rebuilds the posterior on the observations it retains.
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.
Parameters:
all_obs |
Structure of all observations |
conf_info |
Structure of atoms configuration |
update_sexpat_cf_param |
Set to “true” to update parameters of the SexpAt covariance function |
update_const_cf_param |
Set to “true” to update parameters of the Constant covariance function |
update_sqrt_prior_param |
Set to “true” to update parameters of the SQRT prior |
bool 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.
bool 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))).
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)
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.
void markHyperparametersFitted()
Fitted hyperparameters installed from outside the optimizer, e.g. a seed kernel handed over by the band that produced the training rows.
void setOptimizationRowPool(std::vector<bool> pool)
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.
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)
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.
void 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.
void setAdditivePairResiduals(bool enabled)
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.
double activeFitStartForTesting() const
MAP objective at the start of the last active correction fit.
Eigen::Index activeFitAnchorCountForTesting() const
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).
Eigen::Index activeFitSupportCountForTesting() const
Anchors used to condition the selected correction after its support expands beyond the hyperparameter fit subset.
Eigen::Index residualInducingCount() const
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.
bool hasPendingResidualModelRefit() const
Model expansion for a measured error despite small force uncertainty. This does not certify the force or restrict fitting to active lengths.
void setUpDefault()
Set up default parameters.
This function allocates memory for the private pointers and calls for setUpDefault() method on each pointer.
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).
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:
x |
Training input vectors to GP |
x_ind |
Per-row observation type or derivative-channel indices |
cov_matrix |
Noisy covariance matrix for observations y |
serial_per_rank |
Assemble a complete local matrix without a collective reduction |
include_constant |
Include the constant covariance component |
include_noise |
Add observation noise to the diagonal |
const TrainingKernelGeometry* fitGeometryFor(const EigenMatrix& x, const Eigen::VectorXd& x_ind) const
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.
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)
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.
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)
Select derivative outputs independently of the active covariance’s metric. The output contains amplitude followed by requested 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)
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.
bool evaluateGradientAfterEnergy(const Eigen::VectorXd& w, const EigenMatrix& x, const Eigen::VectorXd& x_ind, const Eigen::VectorXd& y, Eigen::VectorXd& gradient)
Gradient at the theta whose factor and kernel evaluateEnergy just built. A mismatched theta returns false so the caller recomputes both.
bool evaluateTrainingCovarianceInFactorOrder(const EigenMatrix& x, const Eigen::VectorXd& x_ind, EigenMatrix& cov_matrix, bool include_noise = true)
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.
bool evaluateTrainingCrossCovarianceInFactorOrder(const EigenMatrix& query, const Eigen::VectorXd& query_ind, EigenMatrix& cross) const
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.
EigenMatrix trainingCrossCovarianceInFactorRows(const EigenMatrix& query, const Eigen::VectorXd& query_ind, bool serial_per_rank) const
The cross-covariance in factor rows, placed when it can be and assembled channel-major and permuted otherwise.
void 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.
int lastRefitKind() const
How the last refresh set the hyperparameters: 0 held theta (stationary), 1 took the one Newton step, 2 ran the optimizer.
double lastStationarityShift() const
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).
bool refreshFullDataPosteriorIfObjectiveStationary(const Observation& full_observation, double* shift_norm_out = nullptr)
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.
double computeLaplaceSkipScgShiftNorm(const EigenMatrix& opt_R_matrix, const Eigen::VectorXd& opt_R_indices, const Eigen::VectorXd& opt_y)
Compatibility wrapper for the Laplace skip-SCG API. Uses the current covariance-function parameter vector as the reference point.
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.
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:
x1 |
First input vector |
x1_ind |
Observation type or derivative-channel indices for rows of x1 |
x2 |
Second input vector |
x2_ind |
Observation type or derivative-channel indices for rows of x2 |
C |
Covariance matrix |
serial_per_rank |
Assemble a complete local matrix without a collective reduction |
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.
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:
w |
Vector of combined parameters from covariance functions and likelihood |
x |
Training input vectors |
x_ind |
Per-row observation type or derivative-channel indices |
y |
Observed target values aligned with the rows of x |
energy_and_gradient |
Output energy and parameter gradient |
void 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.
MarginalLikelihoodReport optimizeMarginalLikelihood(const Observation& observation)
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.
bool appendFixedHyperparameters(const Observation& full_observation)
Append to a fitted posterior at fixed hyperparameters. The existing Cholesky factor must be appendable; otherwise this returns false without rebuilding or optimizing.
ForceCalibrationReport calibrateHeldOutForces(const Observation& held_out, double nominal_probability)
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.
LeaveOneOutCalibrationReport calibrateLeaveOneOut(double nominal_probability) const
Evaluate all training channels by closed-form leave-one-out prediction from the active posterior’s inverse diagonal and weights.
LikelihoodNoiseVarianceUpdate setLikelihoodNoiseVariance(double physical_sigma2, const Observation* full_observation = nullptr)
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_sigma2 |
Positive finite variance in physical output units. |
full_observation |
Optional 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.
bool 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_sigma2 |
Minimum likelihood variance in physical output sigma^2 units. |
full_observation |
Full 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.
void 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.
void 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:
observation |
The full set of observed data. |
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.
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.
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)
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.
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.
void 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:
image1 |
Observation at image 1 |
bool calculateMeanHessianVectorDispatched(const Coord& R, const Eigen::VectorXd& direction, Eigen::VectorXd& hessian_vector)
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.
MixtureMeanHessianStatus calculateLaplaceMixtureMeanHessianVector(const Coord& R, const Eigen::VectorXd& direction, Eigen::VectorXd& hessian_vector)
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.
MeanHessianAction prepareMeanHessian(const Coord& R)
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.
bool calculateMeanHessian(const Coord& R, Eigen::MatrixXd& hessian)
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.
bool calculateExactDirectionalCurvature(const Coord& R, const Eigen::VectorXd& direction, double& curvature)
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.
MeanHessianAction prepareAnalyticMeanHessian(const Coord& R)
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.
void 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.
void 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.
void 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.
void setUncertaintyMode(UncertaintyMode mode)
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).
HyperparameterPosterior retainHyperparameterPosterior()
Materialize and retain the EB/Laplace hyperparameter distribution. Other uncertainty modes return an empty quadrature.
HyperparameterPosterior currentHyperparameterPosterior() const
Retain an existing, current quadrature without estimating a new one.
bool conditionOnHyperparameterPosterior(const HyperparameterPosterior& posterior)
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.
void setUseAlphaKPredictMean(bool use)
Enable the alpha-K contraction for MAP mean prediction.
void setUseAlphaKLaplaceMean(bool use)
Enable the alpha-K contraction for Laplace-mixture mean prediction.
void setFitStepStop(bool use)
Whether the auto stationarity mode also ends each fit at its scale.
void 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).
void 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.
void setMapMeanKernelOverridesHssvdForTesting(bool override)
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.
The fitted mean stays in place. A true exact flag makes a false action a refusal of that call only.
void setHssvdHessianBlockApplyFailsForTesting(bool fail) const
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.
void resetDispatchedMapMeanHessianActionsForTesting() const
Reset the count of exact MAP Hessian actions built by dispatch.
std::size_t getDispatchedMapMeanHessianActionsForTesting() const
Count of exact MAP Hessian actions built by dispatch.
void setPriorMeanStatistic(PriorMeanStatistic statistic)
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.
void setOutputScaleFloor(bool enabled)
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.
void 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.
void restoreOutputTransform(double mean, double scale, bool frozen_mean)
Restore output coordinates alongside a kernel represented in them.
void setPopulationPrior(priors::PopulationPrior prior)
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.
void 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).
void setUseLogNormalMagnPrior(bool use)
Opt-in log-normal prior on magnSigma2 (PriorLogNormal). Off keeps the half-Student-t or half-Cauchy magnitude prior.
void setLengthScaleSeedChemicalFloor(bool enabled)
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”).
void setRobustNu(double nu)
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).
bool 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.
void releaseLengthScaleTieForTesting(Index_t member)
Gives the tie member its own length scale, as the evidence screen does once it has accumulated enough.
int lastTieScreenProbes() const
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.
bool lengthScaleTiesActive(Eigen::Index length_count) const
Whether the packed parameter vector of length_count log lengths is governed by ties.
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
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.
void 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.
void refreshLengthScaleLeaders()
Recomputes the leaders from the released flags.
void setPairLocalTiles(bool enabled)
The pair-local tiles assemble the training covariance and contract its hyperparameter derivatives per configuration pair; off, the per-channel block geometry does both.
void setPairLocalDirectionalTiles(bool enabled)
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.
void setUseFFPriorMean(bool use)
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.
void 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).
void 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.
bool physicalPriorMeanActive() const
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
Exact energy and Cartesian gradient of that prior. False when neither prior is active.
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.
void setUsePsisLaplace(bool use)
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.
void setUsePsisDeterministicGrid(bool use)
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).
void setUseDeltaMethod(bool use)
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.
void setDeltaUHMinDiag(double v)
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.
void 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).
void setRFFFeaturesRequested(int D_rff)
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).
void enableRFFFeatureSelection(double force_tol_fraction = 0.0)
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.
RFFFeatureSelection selectRFFFeatures(const Observation& observation, std::uint64_t memory_cap_bytes = kRFFValidationMemoryCapBytes)
Choose D on observation without installing it. The production cap is kRFFValidationMemoryCapBytes. A smaller cap is only a test of the refusal path.
void setHyperparameterOptimizationMode(HyperparameterOptimizationMode mode)
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.
void setRgminMethod(rgmin_method_t m)
Solver for HyperparameterOptimizationMode::RGMIN_OPT. Applies to the next mode selection as well as the live optimizer, so order of configuration does not matter.
void setVarianceSubsetConfigurations(int configurations)
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.
void setVarianceSubsetFootprint(bool enabled)
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.
void setAnnealStage(bool enabled, std::size_t budget, std::size_t replicas, std::size_t every, std::uint64_t seed)
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.
void noteSurrogateContradiction()
Evidence against the surrogate at a measured point, the trigger of the next anneal stage under the evidence policy.
const AnnealStageSummary& lastAnnealStage() const
The last stage that ran, for diagnostics and tests.
std::size_t lastFitEvaluationsForTesting() const
Objective evaluations of the last hyperparameter fit.
std::size_t rgminWarmStartsForTesting() const
Fits the rgmin sessions opened with the previous fit’s record.
std::size_t rgminWarmPairsForTesting() const
Curvature pairs the last rgmin fit transplanted from that record.
void setRgminWarmStart(bool keep)
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).
void forgetRgminSessions()
Drop the rgmin sessions’ memory: the next fit starts cold. Called when the parameters move to another basin (an anneal stage).
virtual bool exactNlmlHessianVectorAvailable() const
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).
bool nlmlHessianVectorCurvatureRequested() const
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.
int nlmlHessianVectorFallbacks() const
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.
void noteNlmlHessianVectorFallback(const char* where, const char* why)
Counts and logs one such routing: where took the finite_difference path because of why.
void setOptimizationSubsetHistory(int rows)
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.
void setSubsetFailureEscalation(bool enabled)
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.
void setRgminInitialLogMove(double distance)
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.
void setRgminInitialLogMoveWholeSession(bool whole_session)
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.
void setSkipUnchangedSubsetFit(bool enabled)
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.
std::size_t unchangedSubsetFitSkipsForTesting() const
Fits skipped because the subset and the theta were unchanged.
std::size_t lastFitConfigurationsForTesting() const
Training configurations in the objective of the last hyperparameter fit (the farthest-point subset, or every row after an escalation).
bool lastWarmStartInfeasible() const
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.
Eigen::VectorXd fittedKernelParameters() const
The kernel hyperparameters as the optimizer sees them (log magnitude, log length scales); empty without a kernel.
void setWallClockLimit(std::shared_ptr<const WallClockLimit> limit)
Share the enclosing search deadline with every hyperparameter optimizer. A null limit removes the callback.
bool wallClockLimitReached() const
Collective on the model’s process group for distributed fitters.
void setNlmlHessianVectorFailureForTesting(bool fail)
Makes evaluateNlmlHessianVector fail while exactNlmlHessianVectorAvailable() stays true.
void setFitTolerancesForTesting(double objective, double step)
The fit’s objective and step tolerances (the rgmin gradient tolerance is their minimum).
void setObjectiveBackend(ObjectiveBackend backend, Eigen::Index rank = 0)
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.
double fitStepTolerance() const
The fit’s step tolerance: a hyperparameter shift below it is one the optimizer itself treats as no move.
void setRequireScgFallbackImprovement(bool enabled)
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.
int lastFitRestarts() const
Restarts of the last fit; only a marginal-likelihood fit restarts.
bool 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.
bool disableLaplaceFactorsForTesting()
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.
void 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.
bool devicePosteriorLiveForTesting() const
True while the resident device posterior holds the training factor. The host C, L and a are then empty until a reader materializes them.
bool residentTrainingFactorRetainedForTesting() const
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.
bool devicePosteriorCapableForTesting() const
True when conditioning or an objective evaluation takes the device posterior, so host assembly counters and caches stay untouched.
EigenMatrix trainingCovarianceForTesting() const
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.
bool hssvdEnergyDesign(const FieldMatrixd& query, Eigen::VectorXd& design, Eigen::VectorXd& coeff) const
Design row and reduced coefficients of one HS-SVD energy prediction. The standardized energy is their dot product.
bool hssvdLocalPosteriorCovarianceForTesting(const EigenMatrix& positions, const EigenMatrix& prior, EigenMatrix& K_post)
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.
void setDescriptorPredictor(bool enabled)
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.
const char* hyperparameterOptimizationModeName() const
Name of the hyperparameter fit in force, for the run report.
std::size_t lastInlaIterations() const
Newton (RFO) iterations taken by the most recent INLA mode search.
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.
Returns:
False without a dense training factor.
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.
void 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).
void 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.
void calculateVarianceBatch(std::vector<Observation*> queries)
One dispatched variance predict for B same-composition queries.
std::uint64_t factorEpoch() const
Monotone generation of the fitted posterior. Both full-data fits and conditioning on new observations advance the generation.
void 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.
void 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.
void 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.
void 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.
Eigen::VectorXd calculateObservationNoiseDiagonal(const EigenMatrix& positions) const
Physical Gaussian measurement variance, including jitter, in the joint energy-gradient channel order used for sequential conditioning.
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)
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.
void 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.
double calculateObservationFunctionalVariance(const EigenMatrix& positions, const Eigen::VectorXd& weights)
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.
bool conditionActivePosterior(const Observation& full_observation, std::shared_ptr<const KernelOperator> active_kernel = {})
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.
bool fitActivePosterior(const Observation& full_observation, const std::vector<bool>& active_lengths, bool compare_cartesian_residual = false)
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.
bool refreshActivePosterior(const Observation& full_observation)
Condition the fixed active kernel on an extended observation suffix. Returns false when a full fit must replace the retained background.
bool restoreActivePosterior(const ActivePosteriorRestorePoint& point, const Observation& full_observation)
Recondition the retained correction after restoring its background parameters and output coordinates. False denotes an empty restore point; incompatible ownership, coordinates, or observations throw.
std::shared_ptr<const KernelOperator> makeActiveCovarianceOperator(const Eigen::VectorXd& theta, const std::vector<bool>& active_lengths) const
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.
bool 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.
std::size_t distributedFactorAppendsForTesting() const
Rebuilds that appended to the cached distributed factor.
void setJitterSigma2(double value)
Set sigma2 jitter value.
double getJitterSigma2() const
Configured numerical diagonal jitter variance.
void setChainImageCount(int n)
Set the NEB chain image count so optimize() can apply image-count-adaptive length-scale controls where configured.
void setLengthscaleFloor(double floor)
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.
void setParameters(const GPRSetup& parameters)
Set parameters of the GPR model.
void 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.
void 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.
double fitGeodesicHeatPrior(const Coord& reference_path, const Observation& training_data)
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.
void clearGeodesicHeatPrior()
Remove the additive geodesic covariance and restore the configured base-kernel execution backend for hyperparameter fitting.
std::optional<double> inferInternalCoordinateLengthScale(const geometry::InternalCoordinateChart& chart) const
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.
double getSigma2() const
Live physical output-noise variance of the fitted model (the value the resolution-limit admission threshold and RFF path consume).
double getPhysicalTotalDiagonalRegularization() const
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.
double likelihoodNoiseVariance() const
Fitted Gaussian likelihood noise variance sigma_n^2. This is the restricted-variance acquisition floor, not the SE signal scale SexpatCF::getMagnSigma2().
const EigenMatrix& getL() const
Read-only accessors for training-state members consumed by downstream Laplace / TCOV-INLA helpers.
bool hasTrainingCholeskyFactor(Eigen::Index expected_rows) const
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.
bool parkTrainingCholeskyFactor()
Move this model’s distributed training factor out of the process-wide ScaLAPACK solve slot while another GP owns it.
bool 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.
void claimActiveTrainingCholeskyFactor()
Associate the live ScaLAPACK factor with this GP after a materialize.
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.
Parameters:
w |
Vector 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. |
Eigen::VectorXd packInlaHyperparameters() const
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.
void 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.
void clearHierarchicalPrior()
Disable the hierarchical prior set via ~setHierarchicalPrior~. Restores the flat prior path on the SExp kernel.
bool assembleCompositeJointCovariance(const EigenMatrix& x, const Eigen::VectorXd& indices, SexpatCF& covariance, EigenMatrix& result) const
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).
bool assembleCompositeJointCovarianceSecondDerivative(const EigenMatrix& x, const Eigen::VectorXd& indices, SexpatCF& covariance, const Eigen::VectorXd& direction, EigenMatrix& second) const
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.
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.
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.
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.
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.
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
nullopt selects the per-channel representation. A returned false rejects invalid data; true supplies the owned bare kernel derivatives.
bool failedOptim() const
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.
std::size_t nonfiniteMarginalLikelihoodRejections() const
Lifetime count of refits that kept the input theta because the marginal likelihood there was non-finite. The stop reason names the same event.
bool isDecomposedSuccessfully() const
True after the most recent covariance factorization succeeded. Dest INLA lives in a free helper, so it cannot read the protected flag.
const Observation& fittedObservations() const
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.
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.
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.
This function performs the following operation (in MATLAB form):
Note
matrix should be pre-allocated
Parameters:
ind_Ddim1 |
Vector of dimensions used in rows |
ind_Ddim2 |
Vector of dimensions used in columns |
row_val |
Index of row |
col_val |
Index of column |
field |
Reference field |
matrix |
Reference matrix |
transpose_field |
True if the field should be transposed |
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.
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.
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.
Parameters:
column_ind |
Column index |
matrix |
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)
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.
bool tryGateEnergyVarianceInterval(const Observation& query, Eigen::RowVectorXd& energy_variance_lower, Eigen::RowVectorXd& energy_variance_upper)
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.
bool canCertifyEnergyVarianceInterval() const
Whether tryGateEnergyVarianceInterval can certify this model: an exact-kernel HS-SVD MAP posterior with no replacement path active.
bool tryBorderedNoiseReport(BorderedNoiseReport& report) const
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.
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.
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).
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.
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.
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.
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.
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.
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_ind |
unique-index vector (same semantics as evaluateDirectionalCurvature). |
x |
training input matrix. |
y |
training targets. |
n_hyperparameters |
p 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.
bool 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.
bool 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.
void setRetainFittedHyperparameterDensity(bool retain)
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.
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)
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.
void calculatePotentialSVGD(Observation& image1)
SVGD particle posterior predict + variance. Routed via calculatePotentialDispatched / calculateVarianceDispatched when uncertainty-mode=svgd.
void 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.
void 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.
void setSVGDConfig(const laplace::SteinVariationalConfig& cfg)
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.