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

#include <gpr/ml/gp/StableBasis.h>

Classes

struct  SchurFloorReport
 What floorCertifiedSchurDiagonal did to a diagonal. More...
struct  BorderedFactorCache
struct  BorderedRmCache

Public Member Functions

 StableBasisND ()
 StableBasisND (std::shared_ptr< linalg::BackendContext > context)
void setChopNoiseVariance (double sigma2) noexcept
double chopNoiseVariance () const noexcept
double droppedEigenvalueMax () const noexcept
 Largest eigenvalue discarded by the last truncation (0 when none).
double covarianceComplementEigenvalue () const noexcept
 Largest signal eigenvalue represented by the discarded covariance complement.
double complementWeight (double sigma2) const noexcept
double covarianceComplementWeight (double sigma2) const noexcept
void recordDroppedSpectrum (const Eigen::VectorXd &S)
void factorize (const Eigen::MatrixXd &X, const Eigen::VectorXd &eps, double alpha, int max_degree, bool gradient_enhanced, double sv_rtol=1e-13)
void factorizeGPCartesian (const Eigen::MatrixXd &X, const Eigen::VectorXd &eps, double alpha, double overall_scale, int max_degree, const std::vector< Eigen::MatrixXd > &jacobians, bool component_major=false, double sv_rtol=1e-13, int sketch_size=0, int n_power_iter=2, double mode_prune_rtol=0.0, double sv_abs_tol=0.0)
void factorizeGPCartesianAffine (const Eigen::MatrixXd &U, const Eigen::VectorXd &eps, double alpha, double overall_scale, int max_degree, const std::vector< Eigen::MatrixXd > &jac_tangent, const std::vector< Eigen::MatrixXd > &jac_normal, bool component_major=false, double sv_rtol=1e-13, int sketch_size=0, int n_power_iter=2, double mode_prune_rtol=0.0, double sv_abs_tol=0.0)
void factorizeKernel (const Eigen::MatrixXd &kernel, double sv_rtol=1e-13, double sv_abs_tol=0.0, double sv_chop_tol=0.0)
bool factorizeKernelLapackRrr (const Eigen::MatrixXd &kernel, double sv_rtol=1e-13, double sv_abs_tol=0.0, double sv_chop_tol=0.0, bool allow_value_range=false)
void factorizeNoisyKernel (const Eigen::MatrixXd &noisy_kernel, double sigma2)
bool factorizeNoisyKernelLapackRrr (const Eigen::MatrixXd &noisy_kernel, double sigma2)
void factorizeKernelRandomized (const Eigen::MatrixXd &kernel, int sketch_size, int n_power_iter=2, double sv_rtol=1e-13, double sv_abs_tol=0.0, double sv_chop_tol=0.0)
void liftFromDeflatedSubspace (Eigen::Index full_rows, Eigen::MatrixXd lifted_psi, const detail::RigidDeflationState &deflation, double extra_assembly_error=0.0)
bool factorizeKernelAppend (const StableBasisND &old_basis, const Eigen::MatrixXd &cross_old_new, const Eigen::MatrixXd &new_kernel, double sv_rtol=1e-13, double sv_abs_tol=0.0, double sv_chop_tol=0.0)
Eigen::VectorXd solve (const Eigen::VectorXd &y) const
Eigen::VectorXd predictEnergy (const Eigen::MatrixXd &Xstar, const Eigen::VectorXd &b) const
Eigen::MatrixXd predictGradient (const Eigen::MatrixXd &Xstar, const Eigen::VectorXd &b) const
Eigen::VectorXd solveNoisy (const Eigen::VectorXd &y, double sigma2) const
Eigen::VectorXd noisySelfQuadratic (const Eigen::MatrixXd &rhs, double sigma2) const
Eigen::VectorXd noisyRangeSelfQuadratic (const Eigen::MatrixXd &rhs, double sigma2) const
Eigen::VectorXd stableRangePosteriorDiagonal (const Eigen::MatrixXd &rhs, const Eigen::VectorXd &prior, const Eigen::VectorXd &signal, double sigma2, bool check_variance=true) const
 Range-only posterior diagonal as a nonnegative eigenmode sum.
std::vector< BorderedVarianceInterval > noisyBorderedVarianceIntervals (const Eigen::MatrixXd &rhs, const Eigen::VectorXd &prior_diag, double sigma2) const
std::vector< BorderedVarianceInterval > noisyBorderedVarianceIntervals (const Eigen::MatrixXd &rhs, const Eigen::VectorXd &prior_diag, double sigma2, BorderedSchurSign sign) const
 Same enclosure. PreserveSigned keeps a negative Schur value.
BorderedNoiseReport borderedNoiseReport (double sigma2) const
BorderedNoiseReport borderedNoiseReport (double sigma2, double output_variance_scale) const
BorderedNoiseReport borderedNoiseReport (double sigma2, double y_scale, double calibration) const
SchurFloorReport floorCertifiedSchurDiagonal (const Eigen::MatrixXd &cross, const Eigen::VectorXd &prior, double sigma2, Eigen::VectorXd &value, const std::vector< char > *skip=nullptr) const
double trainingRowLatentErrorBound (Eigen::Index row, double sigma2) const
Eigen::Index borderedKernelOrder () const noexcept
bool supportsBorderedVarianceInterval () const noexcept
Eigen::VectorXd noisyInverseDiagonal (double sigma2) const
Eigen::VectorXd noisyInverseDiagonalEntries (const Eigen::VectorXi &rows, double sigma2) const
double leaveOneOutNegativeLogPredictiveDensity (const Eigen::VectorXd &y, double sigma2) const
double computeVarianceCalibrationFactor (const Eigen::VectorXd &y, double sigma2) const
Eigen::VectorXd noisyInverseSandwichDiagonal (const Eigen::MatrixXd &dK, double sigma2) const
double leaveOneOutNegativeLogPredictiveDensityDirectionalDerivative (const Eigen::VectorXd &y, double sigma2, const Eigen::MatrixXd &dK) const
Eigen::MatrixXd noisyInverse (double sigma2) const
double leaveOneOutNegativeLogPredictiveDensityGrouped (const Eigen::VectorXd &y, double sigma2, const std::vector< std::vector< Eigen::Index > > &groups) const
double leaveOneOutNegativeLogPredictiveDensityGroupedDirectionalDerivative (const Eigen::VectorXd &y, double sigma2, const Eigen::MatrixXd &dK, const std::vector< std::vector< Eigen::Index > > &groups) const
Eigen::VectorXd posteriorMeanReducedCoeffs (const Eigen::VectorXd &y, double sigma2) const
StableBasisPosteriorWeights noisyPosteriorWeights (const Eigen::VectorXd &y, double sigma2) const
double logDetNoisy (double sigma2) const
Eigen::VectorXd posteriorMeanWeights (const Eigen::VectorXd &alpha) const
Eigen::VectorXd posteriorMeanEnergy (const Eigen::MatrixXd &Xstar, const Eigen::VectorXd &alpha) const
Eigen::MatrixXd posteriorMeanGradient (const Eigen::MatrixXd &Xstar, const Eigen::VectorXd &alpha) const
Eigen::VectorXd posteriorVarianceEnergy (const Eigen::MatrixXd &Xstar, double sigma2) const
Eigen::VectorXd posteriorVarianceDiagonal (const Eigen::MatrixXd &cross, const Eigen::VectorXd &prior, double sigma2) const
 Cancellation-free posterior diagonal for arbitrary query channels.
Eigen::MatrixXd posteriorCovariance (const Eigen::MatrixXd &cross, const Eigen::MatrixXd &prior, double sigma2) const
 Joint posterior covariance from the same exact eigenmode sums.
double posteriorVarianceAction (const Eigen::MatrixXd &cross, const Eigen::MatrixXd &prior, const Eigen::VectorXd &weights, double sigma2) const
 Variance of a linear action on a joint query covariance, evaluated by the same nonnegative eigenmode decomposition.
Eigen::VectorXd predictEnergyAffine (const Eigen::MatrixXd &Ustar, const Eigen::MatrixXd &residuals, const Eigen::VectorXd &b) const
Eigen::VectorXd energyAffineDesignRow (const Eigen::MatrixXd &Ustar, const Eigen::MatrixXd &residuals) const
Eigen::MatrixXd predictGradientAffine (const Eigen::MatrixXd &Ustar, const Eigen::MatrixXd &residuals, const Eigen::MatrixXd &basis, const Eigen::VectorXd &b) const
Eigen::MatrixXd predictGradientHessianVectorAffine (const Eigen::MatrixXd &Ustar, const Eigen::MatrixXd &residuals, const Eigen::MatrixXd &basis, const Eigen::MatrixXd &tangent_directions, const Eigen::MatrixXd &residual_directions, const Eigen::VectorXd &b) const
Eigen::VectorXd posteriorVarianceEnergyAffine (const Eigen::MatrixXd &Ustar, const Eigen::MatrixXd &residuals, double sigma2) const
double conditionNumber () const
double conditionFlooredNoise (double sigma2) const
double varianceFlooredNoise (double sigma2) const
 Variance-specific likelihood-noise floor for the retained spectrum.
int rank () const
bool usedLapackRrrValueRange () const noexcept
const char * lastKernelFactorizeDriver () const noexcept
int lapackRrrFullSolvesForTesting () const noexcept
int lapackRrrExtensionsForTesting () const noexcept
bool usedLapackRrrValueRangeForTesting () const noexcept
bool usedFastKernelEigensolverForTesting () const noexcept
int borderedFactorBuildsForTesting () const noexcept
void assumeExtendedCertificationForTesting (bool available)
void setRetainedSpectrumForTesting (Eigen::MatrixXd psi, Eigen::VectorXd singular_values)
Eigen::MatrixXd energyDesignForTesting (const Eigen::MatrixXd &Xstar) const
Eigen::MatrixXd affineEnergyDesignForTesting (const Eigen::MatrixXd &Ustar, const Eigen::MatrixXd &residuals, Eigen::VectorXd &kself) const
Eigen::VectorXd rangeVarianceFromDesignForTesting (const Eigen::MatrixXd &A_E, double sigma2) const
const Eigen::MatrixXd & trainingDesignForTesting () const
void borderedEpsKForTesting (double &hi, double &lo, int &operations) const
const Eigen::MatrixXd & borderedKernelForTesting () const
double borderedAssemblyErrorForTesting () const
bool hasCrossCovariance () const
int numBasis () const
Eigen::Index numObs () const
const Eigen::MatrixXd & leftSingularVectors () const
const Eigen::VectorXd & singularValues () const
const Eigen::VectorXd & noisyEigenvalues () const
bool hasNoisyEigenvalues () const
bool permuteObservationRows (const Eigen::VectorXi &source_for_target)
Eigen::MatrixXd reconstructKernel (bool truncated) const
void eigenTensorEpsDerivative (const Eigen::MatrixXd &X, int j, Eigen::MatrixXd &Phi, Eigen::MatrixXd &dPhi_eps) const

Static Public Member Functions

static std::size_t factorizationCount () noexcept
static SchurFloorReport schurFloorTotals () noexcept
 Process-wide totals of SchurFloorReport over every call.
static void resetSchurFloorTotals () noexcept
static double floorLatentVariance (double latent, double error_bound, SchurFloorReport *report) noexcept
static Eigen::Index standardChop (const Eigen::VectorXd &coeffs, double tol)
static int autoMaxDegree (const Eigen::VectorXd &eps, double alpha, int dim, double target_tol, int max_degree_cap=40)
static bool gradedModeCountExceedsLimit (int dim, int max_degree, Eigen::Index limit)
static int capMaxDegreeByModeCount (int dim, int requested_degree, Eigen::Index mode_limit)
static Eigen::MatrixXd affineSpanBasis (const Eigen::MatrixXd &centered_X)
static void projectToAffineSpan (const Eigen::MatrixXd &centered_X, const Eigen::MatrixXd &basis, Eigen::MatrixXd &coords, Eigen::MatrixXd &residuals)
static double conditionFlooredSigma2ForTesting (const Eigen::VectorXd &singular_values, double sigma2, Eigen::Index nobs)
static int designVarianceWorkingDigitsForTesting () noexcept
static long long latentVarianceOperationDepthForTesting (Eigen::Index rank) noexcept

Detailed Description

Definition at line 195 of file StableBasis.h.

Constructor & Destructor Documentation

◆ StableBasisND() [1/2]

gpr::StableBasisND::StableBasisND ( )

Definition at line 629 of file StableBasis.cpp.

630 : backend_context_(std::make_shared<linalg::BackendContext>())
631{
632}

◆ StableBasisND() [2/2]

gpr::StableBasisND::StableBasisND ( std::shared_ptr< linalg::BackendContext > context)
explicit

Definition at line 634 of file StableBasis.cpp.

635 : backend_context_(std::move(context))
636{
637 if (!backend_context_)
638 throw std::invalid_argument("stable basis requires a backend context");
639}

Member Function Documentation

◆ affineEnergyDesignForTesting()

Eigen::MatrixXd gpr::StableBasisND::affineEnergyDesignForTesting ( const Eigen::MatrixXd & Ustar,
const Eigen::MatrixXd & residuals,
Eigen::VectorXd & kself ) const
inline

Definition at line 891 of file StableBasis.h.

894 {
895 Eigen::MatrixXd energy;
896 AffineVariancePrior exact;
897 designAtAffineEnergy(Ustar, residuals, energy, &exact);
898 kself.resize(exact.diagonal.size());
899 // The variance path keeps this diagonal unrounded. Callers that
900 // rebuild a reference in binary64 get an upper bound on it.
901 for (Eigen::Index i = 0; i < exact.diagonal.size(); ++i)
902 kself(i) = gpr::extended::roundUpToDouble(exact.diagonal(i));
903 return energy;
904 }
double roundUpToDouble(Work value)

◆ affineSpanBasis()

Eigen::MatrixXd gpr::StableBasisND::affineSpanBasis ( const Eigen::MatrixXd & centered_X)
static

Definition at line 1823 of file StableBasis.cpp.

1825{
1826 const Eigen::Index d = centered_X.cols();
1827 if (centered_X.rows() == 0 || d == 0) return Eigen::MatrixXd(d, 0);
1828
1829 Eigen::BDCSVD<Eigen::MatrixXd> svd(centered_X, Eigen::ComputeThinV);
1830 const Eigen::VectorXd& S = svd.singularValues();
1831 if (S.size() == 0 || S(0) == 0.0) return Eigen::MatrixXd(d, 0);
1832
1833 const double tol = std::numeric_limits<double>::epsilon() *
1834 static_cast<double>(std::max(centered_X.rows(), d)) *
1835 S(0);
1836 Eigen::Index rank = 0;
1837 while (rank < S.size() && S(rank) > tol)
1838 ++rank;
1839 return svd.matrixV().leftCols(rank);
1840}

◆ assumeExtendedCertificationForTesting()

void gpr::StableBasisND::assumeExtendedCertificationForTesting ( bool available)

Force the extended-precision certificate off, or back on. On cannot succeed where the platform has neither an extended long double nor IEEE binary64 for the double-double fallback. Clears the factor cache.

Definition at line 3231 of file StableBasis.cpp.

3232{
3233 if (available && !gpr::extended::certificationAvailable()) {
3234 throw std::invalid_argument(
3235 "extended certification cannot be enabled on this platform");
3236 }
3237 std::lock_guard<std::mutex> lock(bordered_cache_.mutex);
3238 bordered_cache_.factor.reset();
3239 bordered_cache_.error.clear();
3240 bordered_cache_.rm.reset();
3241 bordered_cache_.extended_override = available ? 1 : 0;
3242}
constexpr bool certificationAvailable()
bool available() noexcept
Definition CutlassGemm.h:43

◆ autoMaxDegree()

int gpr::StableBasisND::autoMaxDegree ( const Eigen::VectorXd & eps,
double alpha,
int dim,
double target_tol,
int max_degree_cap = 40 )
static

Definition at line 931 of file StableBasis.cpp.

933{
934 // The largest sqrt(lambda) at total degree D concentrates the degree in the
935 // slowest-decaying dimension: env(D) = prod_k sqrt(lam0_k) (max_k
936 // sqrt(r_k))^D, a geometric series. standardChop on this per-degree
937 // envelope returns where the Mercer expansion resolves the kernel to
938 // target_tol, giving an eps-adaptive degree in place of a fixed constant.
939 double prod_lam0 = 1.0, max_sqrt_r = 0.0;
940 for (int k = 0; k < dim; ++k) {
941 const double e = eps(k);
942 const double beta = std::pow(1.0 + std::pow(2.0 * e / alpha, 2), 0.25);
943 const double delta2 = alpha * alpha / 2.0 * (beta * beta - 1.0);
944 const double denom = alpha * alpha + delta2 + e * e;
945 const double rr = e * e / denom;
946 const double lam0 = std::sqrt(alpha * alpha / denom);
947 prod_lam0 *= std::sqrt(lam0);
948 max_sqrt_r = std::max(max_sqrt_r, std::sqrt(rr));
949 }
950 Eigen::VectorXd env(max_degree_cap + 1);
951 for (int D = 0; D <= max_degree_cap; ++D)
952 env(D) = prod_lam0 * std::pow(max_sqrt_r, static_cast<double>(D));
953 const int cut = static_cast<int>(standardChop(env, target_tol));
954 int deg = cut - 1; // degrees 0..cut-1 retained
955 if (deg < 1) deg = 1;
956 if (deg > max_degree_cap) deg = max_degree_cap;
957 return deg;
958}
static Eigen::Index standardChop(const Eigen::VectorXd &coeffs, double tol)

◆ borderedAssemblyErrorForTesting()

double gpr::StableBasisND::borderedAssemblyErrorForTesting ( ) const
inlinenodiscard

Definition at line 929 of file StableBasis.h.

930 {
931 return bordered_assembly_error_;
932 }

◆ borderedEpsKForTesting()

void gpr::StableBasisND::borderedEpsKForTesting ( double & hi,
double & lo,
int & operations ) const

The bordered factor's eps_K as hi + lo binary64 limbs, and the number of rounded operations the directed margin on it counts.

Definition at line 4811 of file StableBasis.cpp.

4813{
4814 using Extended = gpr::extended::WorkingReal;
4815 std::lock_guard<std::mutex> lock(bordered_cache_.mutex);
4816 buildBorderedFactorLocked();
4817 const auto factor = bordered_cache_.factor;
4818 hi = static_cast<double>(factor->eps_k);
4819 lo = static_cast<double>(factor->eps_k - static_cast<Extended>(hi));
4820 operations = factor->eps_k_ops;
4821}
std::conditional_t< nativeLongDoubleIsExtended(), long double, DoubleDouble > WorkingReal

◆ borderedFactorBuildsForTesting()

int gpr::StableBasisND::borderedFactorBuildsForTesting ( ) const
inlinenodiscardnoexcept

Definition at line 854 of file StableBasis.h.

855 {
856 std::lock_guard<std::mutex> lock(bordered_cache_.mutex);
857 return bordered_cache_.builds;
858 }

◆ borderedKernelForTesting()

const Eigen::MatrixXd & gpr::StableBasisND::borderedKernelForTesting ( ) const
inlinenodiscard

The exact stored kernel and its binary64 assembly error bound, the two inputs eps_K is derived from.

Definition at line 925 of file StableBasis.h.

926 {
927 return bordered_kernel_;
928 }

◆ borderedKernelOrder()

Eigen::Index gpr::StableBasisND::borderedKernelOrder ( ) const
inlinenodiscardnoexcept

Definition at line 607 of file StableBasis.h.

608 {
609 return bordered_deflation_ ? bordered_deflation_->deflated_rows
610 : Psi_.rows();
611 }

◆ borderedNoiseReport() [1/3]

BorderedNoiseReport gpr::StableBasisND::borderedNoiseReport ( double sigma2) const

Condition-floored noise for the requested sigma2, the certificate gap of the stored kernel factor and the noise the interval certifies. Builds (and caches) the factor, and throws BorderedVarianceError when it cannot be built.

Definition at line 3631 of file StableBasis.cpp.

3632{
3633 return borderedNoiseReport(sigma2, 1.0);
3634}
BorderedNoiseReport borderedNoiseReport(double sigma2) const

◆ borderedNoiseReport() [2/3]

BorderedNoiseReport gpr::StableBasisND::borderedNoiseReport ( double sigma2,
double output_variance_scale ) const

The same report in the units of an output frame scaled by output_variance_scale (a positive finite factor, y_scale^2). The certificate is decided after scaling, from the scaled endpoints: floored is rounded down and certificate_gap up to binary64, so certified holds exactly when the reported floored exceeds the reported gap. A unit gap that survives in training units can collapse under the multiply and is then not certified. requested is rounded down like floored, so floored >= requested still holds, and interval equals floored.

Definition at line 3636 of file StableBasis.cpp.

3638{
3639 if (!(output_variance_scale > 0.0) ||
3640 !std::isfinite(output_variance_scale)) {
3641 throw BorderedVarianceError(
3642 "bordered variance inputs do not match the stable basis");
3643 }
3644 const TrainingNoiseReport training = borderedTrainingNoiseReport(sigma2);
3645 BorderedNoiseReport report;
3646 // requested and floored round the same way, so the floor never lowers the
3647 // reported noise.
3648 double up = 0.0;
3649 gpr::extended::outwardProduct(training.requested, output_variance_scale,
3650 report.requested, up);
3651 gpr::extended::outwardProduct(training.floored, output_variance_scale,
3652 report.floored, up);
3653 report.floor_active = training.floor_active;
3654 // The enclosure is computed at the floored noise, not at a larger one.
3655 report.interval = report.floored;
3656 if (!training.certifiable) {
3657 report.certificate_gap = std::numeric_limits<double>::infinity();
3658 report.certified = false;
3659 return report;
3660 }
3661 // The certificate is decided from the scaled endpoints: floored rounded
3662 // down and the gap rounded up, so a one-unit gap in training units that
3663 // collapses under the multiply is not certified.
3664 double gap_down = 0.0;
3665 gpr::extended::outwardProduct(training.gap, output_variance_scale, gap_down,
3666 report.certificate_gap);
3667 report.certified = report.floored > report.certificate_gap;
3668 return report;
3669}
void outwardProduct(double a, double b, double &down, double &up)

◆ borderedNoiseReport() [3/3]

BorderedNoiseReport gpr::StableBasisND::borderedNoiseReport ( double sigma2,
double y_scale,
double calibration ) const

The same report for the output frame y_scale^2 * calibration, with the scale kept in the working type: it is the outward-rounded enclosure [lower, upper] of y_scale^2 * calibration (varianceScaleEnclosure), not a binary64 y_scale * y_scale. floored and requested are rounded down through lower, certificate_gap up through upper, so the certificate is the strict comparison of the reported endpoints and agrees with the energy variance interval gate. Throws BorderedVarianceError when the enclosure is not positive and finite.

Definition at line 3671 of file StableBasis.cpp.

3674{
3675 using Work = gpr::extended::WorkingReal;
3676 const auto scale =
3677 gpr::extended::varianceScaleEnclosure<Work>(y_scale, calibration);
3678 if (!scale.valid) {
3679 throw BorderedVarianceError(
3680 "bordered variance inputs do not match the stable basis");
3681 }
3682 const TrainingNoiseReport training = borderedTrainingNoiseReport(sigma2);
3683 BorderedNoiseReport report;
3684 report.requested =
3685 gpr::extended::scaledLowerBound(training.requested, scale);
3686 report.floored = gpr::extended::scaledLowerBound(training.floored, scale);
3687 report.floor_active = training.floor_active;
3688 report.interval = report.floored;
3689 if (!training.certifiable) {
3690 report.certificate_gap = std::numeric_limits<double>::infinity();
3691 report.certified = false;
3692 return report;
3693 }
3694 report.certificate_gap =
3695 gpr::extended::scaledUpperBound(training.gap, scale);
3696 report.certified = report.floored > report.certificate_gap;
3697 return report;
3698}
VarianceScaleEnclosure< Work > varianceScaleEnclosure(double y_scale, double calibration)
double scaledUpperBound(double value, const VarianceScaleEnclosure< Work > &scale)
double scaledLowerBound(double value, const VarianceScaleEnclosure< Work > &scale)

◆ capMaxDegreeByModeCount()

int gpr::StableBasisND::capMaxDegreeByModeCount ( int dim,
int requested_degree,
Eigen::Index mode_limit )
static

Definition at line 978 of file StableBasis.cpp.

980{
981 if (requested_degree <= 0) return 0;
982 if (mode_limit <= 0) return 0;
983 int degree = requested_degree;
984 while (degree > 0 && gradedModeCountExceedsLimit(dim, degree, mode_limit))
985 --degree;
986 return degree;
987}
static bool gradedModeCountExceedsLimit(int dim, int max_degree, Eigen::Index limit)

◆ chopNoiseVariance()

double gpr::StableBasisND::chopNoiseVariance ( ) const
inlinenodiscardnoexcept

Definition at line 206 of file StableBasis.h.

207 {
208 return chop_sigma2_;
209 }

◆ complementWeight()

double gpr::StableBasisND::complementWeight ( double sigma2) const
inlinenodiscardnoexcept

Weight of the complement (I - Psi Psi^T) in (K + sigma2 I)^-1: 1/(dropped_s2_max + sigma2), the lower end of the exact range.

Definition at line 226 of file StableBasis.h.

227 {
228 // A full orthogonal basis has no complement. Its rounded projector
229 // residual must not be amplified by the inverse noise variance.
230 if (Psi_.cols() == Psi_.rows()) return 0.0;
231 // The exact weight of a dropped component in (K + sigma2 I)^-1 lies
232 // in [1/(s2_drop_max + sigma2), 1/sigma2]; the lower end never
233 // overshoots the explicit posterior and is exact to
234 // s2_drop_max/sigma2 relative. It applies to the targets too: the
235 // observation noise lives in the null directions of K, and the
236 // weights carry y_null/sigma2 exactly as the dense factor does.
237 // Callers form the complement from residual vectors, never from a
238 // difference of squared norms, so rounding in a null direction
239 // enters as norm(r)^2 ~ eps^2 and not as eps/sigma2.
240 const double d = dropped_s2_max_ + sigma2;
241 return (d > 0.0 && std::isfinite(d)) ? 1.0 / d : 0.0;
242 }

◆ computeVarianceCalibrationFactor()

double gpr::StableBasisND::computeVarianceCalibrationFactor ( const Eigen::VectorXd & y,
double sigma2 ) const

Definition at line 4050 of file StableBasis.cpp.

4052{
4053 if (y.size() < 2 || y.size() != Psi_.rows()) return 1.0;
4054 const Eigen::VectorXd alpha = solveNoisy(y, sigma2);
4055 const Eigen::VectorXd q = noisyInverseDiagonal(sigma2);
4056 return looVarianceCalibrationFactor(alpha, q);
4057}
@ y
Definition Enums.h:28
Eigen::VectorXd noisyInverseDiagonal(double sigma2) const
Eigen::VectorXd solveNoisy(const Eigen::VectorXd &y, double sigma2) const
double looVarianceCalibrationFactor(const Eigen::VectorXd &alpha, const Eigen::VectorXd &inv_diag)

◆ conditionFlooredNoise()

double gpr::StableBasisND::conditionFlooredNoise ( double sigma2) const
nodiscard

Condition-floored likelihood noise for this basis' retained spectrum: the same floor every mean/logdet/LOO/variance path applies, exposed so external covariance assembly inverts the SAME regularized operator.

Definition at line 3032 of file StableBasis.cpp.

3033{
3034 return conditionFlooredSigma2(Sr_, sigma2, Psi_.rows());
3035}

◆ conditionFlooredSigma2ForTesting()

double gpr::StableBasisND::conditionFlooredSigma2ForTesting ( const Eigen::VectorXd & singular_values,
double sigma2,
Eigen::Index nobs )
staticnodiscard

The condition floor of a descending singular spectrum, as conditionFlooredNoise computes it from the retained one.

Definition at line 3042 of file StableBasis.cpp.

3044{
3045 return conditionFlooredSigma2(singular_values, sigma2, nobs);
3046}

◆ conditionNumber()

double gpr::StableBasisND::conditionNumber ( ) const

Definition at line 4717 of file StableBasis.cpp.

4718{
4719 return condition_number_;
4720}

◆ covarianceComplementEigenvalue()

double gpr::StableBasisND::covarianceComplementEigenvalue ( ) const
inlinenodiscardnoexcept

Largest signal eigenvalue represented by the discarded covariance complement.

A complement below the eigensolver's backward-error threshold is the null space of the retained model and therefore has eigenvalue zero.

Definition at line 220 of file StableBasis.h.

221 {
222 return dropped_s2_max_;
223 }

◆ covarianceComplementWeight()

double gpr::StableBasisND::covarianceComplementWeight ( double sigma2) const
inlinenodiscardnoexcept

Complement weight for posterior covariance: 1/(max(dropped_s2_max, n eps s2_max) + sigma2).

A dropped eigenvalue below the resolution n eps s2_max is recorded as zero, so complementWeight gives it 1/sigma2. That overshoots its exact weight 1/(s2 + sigma2) by s2/sigma2 relative, which is O(1) once sigma2 sits at the condition floor (itself ~ n eps s2_max). A joint covariance K - K* W K* with W above (K + sigma2 I)^-1 in any direction is indefinite, and the training-row identity sigma2 I - sigma2^2 W pairs a zero complement variance with a nonzero mixed entry. Bounding the dropped spectrum by the resolution keeps W <= (K + sigma2 I)^-1: every covariance block then conditions the prior Psi S^2 Psi^T + (1/w_c - sigma2)(I - Psi Psi^T) >= K on the same observations. The bound is fixed by the factorization, not by the eigensolver's rounding, so it does not move between evaluations.

Definition at line 258 of file StableBasis.h.

260 {
261 if (Psi_.cols() == Psi_.rows()) return 0.0;
262 // maxCoeff rather than Sr_(0): the bound must not depend on every
263 // factorization path storing the spectrum in descending order.
264 const double s_max = Sr_.size() > 0 ? Sr_.cwiseAbs().maxCoeff() : 0.0;
265 const double s2_max = std::isfinite(s_max) ? s_max * s_max : 0.0;
266 const double resolution =
267 static_cast<double>(std::max<Eigen::Index>(1, Psi_.rows())) *
268 std::numeric_limits<double>::epsilon() * s2_max;
269 const double d = std::max(dropped_s2_max_, resolution) + sigma2;
270 return (d > 0.0 && std::isfinite(d)) ? 1.0 / d : 0.0;
271 }

◆ designVarianceWorkingDigitsForTesting()

int gpr::StableBasisND::designVarianceWorkingDigitsForTesting ( )
staticnodiscardnoexcept

Significand digits of the working type the design-variance accumulation runs in.

Definition at line 4800 of file StableBasis.cpp.

4801{
4802 return std::numeric_limits<DesignVarianceReal>::digits;
4803}

◆ droppedEigenvalueMax()

double gpr::StableBasisND::droppedEigenvalueMax ( ) const
inlinenodiscardnoexcept

Largest eigenvalue discarded by the last truncation (0 when none).

Definition at line 211 of file StableBasis.h.

212 {
213 return dropped_s2_max_;
214 }

◆ eigenTensorEpsDerivative()

void gpr::StableBasisND::eigenTensorEpsDerivative ( const Eigen::MatrixXd & X,
int j,
Eigen::MatrixXd & Phi,
Eigen::MatrixXd & dPhi_eps ) const

Definition at line 1974 of file StableBasis.cpp.

1977{
1978 const Eigen::Index m = X.rows();
1979 const Eigen::Index N = midx_.rows();
1980 // Per-(point,dim) 1D tables; dim j also carries d phi_n/d eps_j.
1981 std::vector<std::vector<Eigen::VectorXd>> V(m);
1982 std::vector<Eigen::VectorXd> dVj(m);
1983 for (Eigen::Index i = 0; i < m; ++i) {
1984 V[i].resize(dim_);
1985 for (int k = 0; k < dim_; ++k) {
1986 if (k == j) {
1987 eigen1dEpsDerivative(X(i, k), k, V[i][k], dVj[i]);
1988 } else {
1989 Eigen::VectorXd d;
1990 eigen1d(X(i, k), k, V[i][k], d);
1991 }
1992 }
1993 }
1994 Phi.setOnes(m, N);
1995 dPhi_eps.setZero(m, N);
1996 for (Eigen::Index c = 0; c < N; ++c)
1997 for (Eigen::Index i = 0; i < m; ++i) {
1998 double p = 1.0, dp = 1.0; // product rule: dim j uses d phi/d eps_j
1999 for (int k = 0; k < dim_; ++k) {
2000 p *= V[i][k](midx_(c, k));
2001 dp *= (k == j) ? dVj[i](midx_(c, k)) : V[i][k](midx_(c, k));
2002 }
2003 Phi(i, c) = p;
2004 dPhi_eps(i, c) = dp;
2005 }
2006}

◆ energyAffineDesignRow()

Eigen::VectorXd gpr::StableBasisND::energyAffineDesignRow ( const Eigen::MatrixXd & Ustar,
const Eigen::MatrixXd & residuals ) const

Definition at line 2654 of file StableBasis.cpp.

2656{
2657 Eigen::MatrixXd A_E;
2658 designAtAffineEnergy(Ustar, residuals, A_E);
2659 if (A_E.rows() < 1) return {};
2660 return (A_E * W_).row(0).transpose();
2661}

◆ energyDesignForTesting()

Eigen::MatrixXd gpr::StableBasisND::energyDesignForTesting ( const Eigen::MatrixXd & Xstar) const
inline

Definition at line 884 of file StableBasis.h.

885 {
886 Eigen::MatrixXd energy;
887 std::vector<Eigen::MatrixXd> gradient;
888 designAt(Xstar, energy, gradient);
889 return energy;
890 }

◆ factorizationCount()

std::size_t gpr::StableBasisND::factorizationCount ( )
staticnoexcept

Process-wide count of kernel eigenfactorizations (full and append), the O(m^3) operations of this backend; read per outer iteration by the driver's report line.

Definition at line 992 of file StableBasis.cpp.

993{
994 return g_stable_basis_factorizations.load(std::memory_order_relaxed);
995}

◆ factorize()

void gpr::StableBasisND::factorize ( const Eigen::MatrixXd & X,
const Eigen::VectorXd & eps,
double alpha,
int max_degree,
bool gradient_enhanced,
double sv_rtol = 1e-13 )

Definition at line 2083 of file StableBasis.cpp.

2087{
2088 bordered_kernel_.resize(0, 0);
2089 bordered_assembly_error_ = 0.0;
2090 clearBorderedCache();
2091 lapack_rrr_value_range_used_ = false;
2092 condition_number_ = 0.0;
2093 dim_ = static_cast<int>(X.cols());
2094 M_ = static_cast<int>(X.rows());
2095 alpha_ = alpha;
2096 max_degree_ = max_degree;
2097 gradient_enhanced_ = gradient_enhanced;
2098 affine_full_dim_ = 0;
2099 overall_scale_ = 1.0;
2100 eps_ = eps;
2101 // Per-dimension Fasshauer-McCourt constants.
2102 beta_.resize(dim_);
2103 delta2_.resize(dim_);
2104 Eigen::VectorXd r(dim_), lam0(dim_);
2105 for (int k = 0; k < dim_; ++k) {
2106 const double e = eps_(k);
2107 beta_(k) = std::pow(1.0 + std::pow(2.0 * e / alpha, 2), 0.25);
2108 delta2_(k) = alpha * alpha / 2.0 * (beta_(k) * beta_(k) - 1.0);
2109 const double denom = alpha * alpha + delta2_(k) + e * e;
2110 r(k) = e * e / denom;
2111 lam0(k) = std::sqrt(alpha * alpha / denom);
2112 }
2113 midx_ = gradedMultiIndices(dim_, max_degree);
2114 const Eigen::Index N = midx_.rows();
2115 // sqrt(lambda_alpha) = prod_k sqrt(lam0_k) * sqrt(r_k)^{alpha_k}.
2116 sqrt_lam_.resize(N);
2117 for (Eigen::Index c = 0; c < N; ++c) {
2118 double s = 1.0;
2119 for (int k = 0; k < dim_; ++k)
2120 s *= std::sqrt(lam0(k)) * std::pow(std::sqrt(r(k)), midx_(c, k));
2121 sqrt_lam_(c) = s;
2122 }
2123
2124 // Stacked design A_full = [Phi ; dPhi rows] diag(sqrt_lam).
2125 Eigen::MatrixXd Phi;
2126 std::vector<Eigen::MatrixXd> dPhi;
2127 eigenTensor(X, gradient_enhanced_, Phi, dPhi);
2128 const Eigen::Index nobs = gradient_enhanced_ ? M_ * (1 + dim_) : M_;
2129 Eigen::MatrixXd A(nobs, N);
2130 A.topRows(M_) = Phi;
2131 if (gradient_enhanced_)
2132 for (int i = 0; i < M_; ++i)
2133 for (int j = 0; j < dim_; ++j)
2134 A.row(M_ + i * dim_ + j) = dPhi[j].row(i);
2135 A.array().rowwise() *= sqrt_lam_.transpose().array();
2136
2137 // Thin SVD + Mercer-tail truncation (cf. StableBasis1D::factorize).
2138 Eigen::BDCSVD<Eigen::MatrixXd> svd(
2139 A, Eigen::ComputeThinU | Eigen::ComputeThinV);
2140 const Eigen::VectorXd& S = svd.singularValues();
2141 const double thresh = sv_rtol * S(0);
2142 rank_ = 0;
2143 while (rank_ < S.size() && S(rank_) > thresh)
2144 ++rank_;
2146 const Eigen::MatrixXd Vr = svd.matrixV().leftCols(rank_);
2147 Sr_ = S.head(rank_);
2148 W_ = Vr.array().rowwise() / Sr_.transpose().array();
2149 // Psi = U[:,kept] taken DIRECTLY from the SVD: A W = A (V/S) = U exactly,
2150 // so svd.matrixU() avoids the A*W GEMM (~37% of the decompose, the largest
2151 // single cost) AND is strictly more orthonormal -- A*W divides by the
2152 // ~1e-13 threshold singular value, drifting Psi^T Psi from I by ~3e-6,
2153 // which the solveNoisy projector (1/sigma2)(y - Psi Psi^T y) then
2154 // amplifies. W_ is still kept for the prediction path (predictEnergy = A_E
2155 // W b).
2156 Psi_ = svd.matrixU().leftCols(rank_);
2157 // Thin U is orthonormal only to a few ulps. Off-diagonal gram entries,
2158 // divided by a small retained singular value, push an in-range
2159 // cancellation past the local roundoff. The nearest orthonormal factor
2160 // of those columns, applied to W as well, leaves the diagonal at the
2161 // column-norm residue and keeps A W aligned with Psi.
2162 if (rank_ > 0) {
2163 const Eigen::MatrixXd gram = Psi_.transpose() * Psi_;
2164 Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> gram_solver(gram);
2165 if (gram_solver.info() == Eigen::Success &&
2166 gram_solver.eigenvalues()(0) > 0.0) {
2167 const Eigen::VectorXd inv_sqrt =
2168 gram_solver.eigenvalues().cwiseSqrt().cwiseInverse();
2169 const Eigen::MatrixXd polar =
2170 gram_solver.eigenvectors() * inv_sqrt.asDiagonal() *
2171 gram_solver.eigenvectors().transpose();
2172 Psi_ = Psi_ * polar;
2173 W_ = W_ * polar;
2174 }
2175 }
2176 A_train_ =
2177 A; // retained for the noisy-GP cross-covariance k*(x*) = A(x*) A^T
2178 condition_number_ = rank_ > 0 ? 1.0 : 0.0;
2179}
void recordDroppedSpectrum(const Eigen::VectorXd &S)

◆ factorizeGPCartesian()

void gpr::StableBasisND::factorizeGPCartesian ( const Eigen::MatrixXd & X,
const Eigen::VectorXd & eps,
double alpha,
double overall_scale,
int max_degree,
const std::vector< Eigen::MatrixXd > & jacobians,
bool component_major = false,
double sv_rtol = 1e-13,
int sketch_size = 0,
int n_power_iter = 2,
double mode_prune_rtol = 0.0,
double sv_abs_tol = 0.0 )

Definition at line 2181 of file StableBasis.cpp.

2187{
2188 validateJointJacobians(X, jacobians);
2189 bordered_kernel_.resize(0, 0);
2190 bordered_assembly_error_ = 0.0;
2191 clearBorderedCache();
2192 lapack_rrr_value_range_used_ = false;
2193 condition_number_ = 0.0;
2194 dim_ = static_cast<int>(X.cols());
2195 M_ = static_cast<int>(X.rows());
2196 alpha_ = alpha;
2197 max_degree_ = max_degree;
2198 gradient_enhanced_ = true;
2199 affine_full_dim_ = 0;
2200 overall_scale_ = overall_scale;
2201 eps_ = eps;
2202 beta_.resize(dim_);
2203 delta2_.resize(dim_);
2204 Eigen::VectorXd r(dim_), lam0(dim_);
2205 for (int k = 0; k < dim_; ++k) {
2206 const double e = eps_(k);
2207 beta_(k) = std::pow(1.0 + std::pow(2.0 * e / alpha, 2), 0.25);
2208 delta2_(k) = alpha * alpha / 2.0 * (beta_(k) * beta_(k) - 1.0);
2209 const double denom = alpha * alpha + delta2_(k) + e * e;
2210 r(k) = e * e / denom;
2211 lam0(k) = std::sqrt(alpha * alpha / denom);
2212 }
2213 midx_ = gradedMultiIndices(dim_, max_degree);
2214 // sqrt(lambda_alpha), with the overall kernel scale magnSigma2 folded in:
2215 // K = A A^T scales by overall_scale when sqrt_lam *= sqrt(overall_scale).
2216 const double scl = std::sqrt(overall_scale);
2217 buildSqrtLamAndPrune(r, lam0, scl, mode_prune_rtol);
2218 const Eigen::Index N = midx_.rows();
2219
2220 // Eigenfunctions Phi (M x N) and descriptor gradients dPhi[k] (M x N).
2221 Eigen::MatrixXd Phi;
2222 std::vector<Eigen::MatrixXd> dPhi;
2223 eigenTensor(X, /*want_grad=*/true, Phi, dPhi);
2224
2225 Eigen::Index ngrad = 0;
2226 for (const auto& J: jacobians)
2227 ngrad += J.cols();
2228 const Eigen::Index nobs = static_cast<Eigen::Index>(M_) + ngrad;
2229 Eigen::MatrixXd A(nobs, N);
2230 A.topRows(M_) = Phi; // energy rows (sqrt_lam applied below)
2231 // Cartesian-force rows: contract the descriptor-gradient features with the
2232 // descriptor Jacobian column. config i, component c ->
2233 // row = sum_k dPhi[k](i,:) * J_i(k,c).
2234 // component_major: rows ordered [comp 0 across configs, comp 1 across
2235 // configs, ...] to match the GP's G-column-major target; else config-major.
2236 // Cartesian-force row (config i, component c): contract the descriptor-
2237 // gradient features with the descriptor Jacobian column. The per-(i,c) AXPY
2238 // here beats a per-config GEMM because the contraction dim (dim_, ~3) is
2239 // too small for BLAS GEMM to amortize its overhead + the dPhi gather
2240 // (cachegrind: GEMM 330M vs AXPY 326M/solve, measured at 47c88ac7).
2241 auto force_row = [&](int i, Eigen::Index c) {
2242 Eigen::RowVectorXd g = Eigen::RowVectorXd::Zero(N);
2243 for (int k = 0; k < dim_; ++k)
2244 g += jacobians[i](k, c) * dPhi[k].row(i);
2245 return g;
2246 };
2247 Eigen::Index row = M_;
2248 if (component_major) {
2249 const Eigen::Index C = jacobians.empty() ? 0 : jacobians[0].cols();
2250 for (Eigen::Index c = 0; c < C; ++c)
2251 for (int i = 0; i < M_; ++i)
2252 A.row(row++) = force_row(i, c);
2253 } else {
2254 for (int i = 0; i < M_; ++i)
2255 for (Eigen::Index c = 0; c < jacobians[i].cols(); ++c)
2256 A.row(row++) = force_row(i, c);
2257 }
2258 A.array().rowwise() *= sqrt_lam_.transpose().array();
2259
2260 if (sketch_size > 0 && sketch_size < nobs) {
2261 factorizeFromDesignRandomized(A, sketch_size, n_power_iter, sv_rtol,
2262 sv_abs_tol);
2263 return;
2264 }
2265
2266 Eigen::BDCSVD<Eigen::MatrixXd> svd(
2267 A, Eigen::ComputeThinU | Eigen::ComputeThinV);
2268 const Eigen::VectorXd& S = svd.singularValues();
2269 rank_ = static_cast<int>(
2270 keptSingularRank(S, singularCutoff(S, sv_rtol, sv_abs_tol)));
2272 const Eigen::MatrixXd Vr = svd.matrixV().leftCols(rank_);
2273 Sr_ = S.head(rank_);
2274 W_ = Vr.array().rowwise() / Sr_.transpose().array();
2275 // Psi = U[:,kept] taken DIRECTLY from the SVD: A W = A (V/S) = U exactly,
2276 // so svd.matrixU() avoids the A*W GEMM (~37% of the decompose, the largest
2277 // single cost) AND is strictly more orthonormal -- A*W divides by the
2278 // ~1e-13 threshold singular value, drifting Psi^T Psi from I by ~3e-6,
2279 // which the solveNoisy projector (1/sigma2)(y - Psi Psi^T y) then
2280 // amplifies. W_ is still kept for the prediction path (predictEnergy = A_E
2281 // W b).
2282 Psi_ = svd.matrixU().leftCols(rank_);
2283 A_train_ = A;
2284 condition_number_ = rank_ > 0 ? 1.0 : 0.0;
2285}

◆ factorizeGPCartesianAffine()

void gpr::StableBasisND::factorizeGPCartesianAffine ( const Eigen::MatrixXd & U,
const Eigen::VectorXd & eps,
double alpha,
double overall_scale,
int max_degree,
const std::vector< Eigen::MatrixXd > & jac_tangent,
const std::vector< Eigen::MatrixXd > & jac_normal,
bool component_major = false,
double sv_rtol = 1e-13,
int sketch_size = 0,
int n_power_iter = 2,
double mode_prune_rtol = 0.0,
double sv_abs_tol = 0.0 )

Definition at line 2287 of file StableBasis.cpp.

2294{
2295 validateJointAffineJacobians(U, jac_tangent, jac_normal);
2296 bordered_kernel_.resize(0, 0);
2297 bordered_assembly_error_ = 0.0;
2298 clearBorderedCache();
2299 lapack_rrr_value_range_used_ = false;
2300 condition_number_ = 0.0;
2301 dim_ = static_cast<int>(U.cols());
2302 M_ = static_cast<int>(U.rows());
2303 alpha_ = alpha;
2304 max_degree_ = max_degree;
2305 gradient_enhanced_ = true;
2306 affine_full_dim_ = jac_normal.empty() ? 0 : jac_normal[0].rows();
2307 overall_scale_ = overall_scale;
2308 eps_ = eps;
2309 beta_.resize(dim_);
2310 delta2_.resize(dim_);
2311 Eigen::VectorXd r(dim_), lam0(dim_);
2312 for (int k = 0; k < dim_; ++k) {
2313 const double e = eps_(k);
2314 beta_(k) = std::pow(1.0 + std::pow(2.0 * e / alpha, 2), 0.25);
2315 delta2_(k) = alpha * alpha / 2.0 * (beta_(k) * beta_(k) - 1.0);
2316 const double denom = alpha * alpha + delta2_(k) + e * e;
2317 r(k) = e * e / denom;
2318 lam0(k) = std::sqrt(alpha * alpha / denom);
2319 }
2320 midx_ = gradedMultiIndices(dim_, max_degree);
2321 const double scl = std::sqrt(overall_scale);
2322 buildSqrtLamAndPrune(r, lam0, scl, mode_prune_rtol);
2323 const Eigen::Index N = midx_.rows();
2324 const Eigen::Index ncols = N * (1 + affine_full_dim_);
2325
2326 Eigen::MatrixXd Phi;
2327 std::vector<Eigen::MatrixXd> dPhi;
2328 eigenTensor(U, /*want_grad=*/true, Phi, dPhi);
2329 Eigen::MatrixXd Phi_s =
2330 Phi.array().rowwise() * sqrt_lam_.transpose().array();
2331 std::vector<Eigen::MatrixXd> dPhi_s(dim_);
2332 for (int k = 0; k < dim_; ++k)
2333 dPhi_s[k] = dPhi[k].array().rowwise() * sqrt_lam_.transpose().array();
2334
2335 Eigen::Index ngrad = 0;
2336 for (const auto& J: jac_tangent)
2337 ngrad += J.cols();
2338 const Eigen::Index nobs = static_cast<Eigen::Index>(M_) + ngrad;
2339 Eigen::MatrixXd A = Eigen::MatrixXd::Zero(nobs, ncols);
2340 A.block(0, 0, M_, N) = Phi_s;
2341
2342 const double sqrt2 = std::sqrt(2.0);
2343 auto fill_force_row = [&](Eigen::Index row, int i, Eigen::Index comp) {
2344 Eigen::RowVectorXd tangent = Eigen::RowVectorXd::Zero(N);
2345 for (int k = 0; k < dim_; ++k)
2346 tangent += jac_tangent[i](k, comp) * dPhi_s[k].row(i);
2347 A.block(row, 0, 1, N) = tangent;
2348 for (Eigen::Index p = 0; p < affine_full_dim_; ++p) {
2349 A.block(row, (p + 1) * N, 1, N) =
2350 sqrt2 * jac_normal[i](p, comp) * Phi_s.row(i);
2351 }
2352 };
2353
2354 Eigen::Index row = M_;
2355 if (component_major) {
2356 const Eigen::Index C = jac_tangent.empty() ? 0 : jac_tangent[0].cols();
2357 for (Eigen::Index comp = 0; comp < C; ++comp)
2358 for (int i = 0; i < M_; ++i)
2359 fill_force_row(row++, i, comp);
2360 } else {
2361 for (int i = 0; i < M_; ++i)
2362 for (Eigen::Index comp = 0; comp < jac_tangent[i].cols(); ++comp)
2363 fill_force_row(row++, i, comp);
2364 }
2365
2366 if (sketch_size > 0 && sketch_size < nobs) {
2367 factorizeFromDesignRandomized(A, sketch_size, n_power_iter, sv_rtol,
2368 sv_abs_tol);
2369 return;
2370 }
2371
2372 Eigen::BDCSVD<Eigen::MatrixXd> svd(
2373 A, Eigen::ComputeThinU | Eigen::ComputeThinV);
2374 const Eigen::VectorXd& S = svd.singularValues();
2375 rank_ = static_cast<int>(
2376 keptSingularRank(S, singularCutoff(S, sv_rtol, sv_abs_tol)));
2378 const Eigen::MatrixXd Vr = svd.matrixV().leftCols(rank_);
2379 Sr_ = S.head(rank_);
2380 W_ = Vr.array().rowwise() / Sr_.transpose().array();
2381 Psi_ = svd.matrixU().leftCols(rank_);
2382 A_train_ = A;
2383 condition_number_ = rank_ > 0 ? 1.0 : 0.0;
2384}

◆ factorizeKernel()

void gpr::StableBasisND::factorizeKernel ( const Eigen::MatrixXd & kernel,
double sv_rtol = 1e-13,
double sv_abs_tol = 0.0,
double sv_chop_tol = 0.0 )

Definition at line 1023 of file StableBasis.cpp.

1026{
1027 bordered_kernel_.resize(0, 0);
1028 bordered_assembly_error_ = 0.0;
1029 clearBorderedCache();
1030 ScopedPhaseTimer factorization_timer(PhaseTimers::factorization_seconds);
1032 PhaseTimers::factorization_rows += kernel.rows();
1033 g_stable_basis_factorizations.fetch_add(1, std::memory_order_relaxed);
1034 lapack_rrr_value_range_used_ = false;
1035 fast_kernel_eigensolver_used_ = false;
1036 last_kernel_factorize_driver_ = "eigen";
1037 condition_number_ = 0.0;
1038 dim_ = 0;
1039 M_ = static_cast<int>(kernel.rows());
1040 max_degree_ = 0;
1041 gradient_enhanced_ = true;
1042 affine_full_dim_ = 0;
1043 midx_.resize(0, 0);
1044 sqrt_lam_.resize(0);
1045 W_.resize(0, 0);
1046 A_train_.resize(0, 0);
1047 noisy_eigvals_.resize(0);
1048
1049 if (kernel.rows() == 0 || kernel.rows() != kernel.cols()) {
1050 rank_ = 0;
1051 Psi_.resize(kernel.rows(), 0);
1052 Sr_.resize(0);
1053 return;
1054 }
1055
1056 Eigen::MatrixXd sym = 0.5 * (kernel + kernel.transpose());
1057 bordered_assembly_error_ = kernelAssemblyErrorBound(kernel, sym);
1058 Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> es =
1059 timedSymmetricEigen(sym);
1060 if (es.info() != Eigen::Success || es.eigenvalues().size() == 0) {
1061 rank_ = 0;
1062 Psi_.resize(kernel.rows(), 0);
1063 Sr_.resize(0);
1064 return;
1065 }
1066
1067 Eigen::VectorXd evals_asc = es.eigenvalues();
1068 Eigen::MatrixXd evecs_asc = es.eigenvectors();
1069 gpr::linalg::canonicalizeEigenpairs(evals_asc, evecs_asc);
1070 const Eigen::Index n = evals_asc.size();
1071 Eigen::VectorXd S(n);
1072 for (Eigen::Index i = 0; i < n; ++i) {
1073 const Eigen::Index src = n - 1 - i;
1074 S(i) = std::sqrt(std::max(0.0, evals_asc(src)));
1075 }
1076
1077 rank_ = static_cast<int>(keptSingularRankWithChop(
1078 S, dualKernelSingularCutoff(S, sv_rtol, sv_abs_tol), sv_chop_tol,
1079 chop_sigma2_));
1081 Sr_ = S.head(rank_);
1082 Psi_.resize(kernel.rows(), rank_);
1083 for (Eigen::Index i = 0; i < rank_; ++i) {
1084 const Eigen::Index src = n - 1 - i;
1085 Psi_.col(i) = evecs_asc.col(src);
1086 }
1087 bordered_kernel_ = std::move(sym);
1088 condition_number_ = rank_ > 0 ? 1.0 : 0.0;
1089}
void canonicalizeEigenpairs(Eigen::Ref< Eigen::VectorXd > evals, Eigen::Ref< Eigen::MatrixXd > evecs)
evals has one entry per leading column of evecs. Both are rewritten.
static long factorization_rows
static int factorization_count
static double factorization_seconds

◆ factorizeKernelAppend()

bool gpr::StableBasisND::factorizeKernelAppend ( const StableBasisND & old_basis,
const Eigen::MatrixXd & cross_old_new,
const Eigen::MatrixXd & new_kernel,
double sv_rtol = 1e-13,
double sv_abs_tol = 0.0,
double sv_chop_tol = 0.0 )

Definition at line 1588 of file StableBasis.cpp.

1593{
1594 const Eigen::MatrixXd& old_bordered = old_basis.bordered_kernel_;
1595 const double old_asm_error = old_basis.bordered_assembly_error_;
1596 bordered_kernel_.resize(0, 0);
1597 bordered_assembly_error_ = 0.0;
1598 clearBorderedCache();
1599 g_stable_basis_factorizations.fetch_add(1, std::memory_order_relaxed);
1600 lapack_rrr_value_range_used_ = false;
1601 fast_kernel_eigensolver_used_ = false;
1602 condition_number_ = 0.0;
1603 dim_ = 0;
1604 M_ = static_cast<int>(old_basis.numObs() + new_kernel.rows());
1605 max_degree_ = 0;
1606 gradient_enhanced_ = true;
1607 affine_full_dim_ = 0;
1608 overall_scale_ = 1.0;
1609 eps_.resize(0);
1610 beta_.resize(0);
1611 delta2_.resize(0);
1612 midx_.resize(0, 0);
1613 sqrt_lam_.resize(0);
1614 W_.resize(0, 0);
1615 A_train_.resize(0, 0);
1616
1617 const Eigen::Index n_old = old_basis.numObs();
1618 const Eigen::Index n_new = new_kernel.rows();
1619 const Eigen::Index r_old = old_basis.rank();
1620 if (n_old <= 0 || n_new <= 0 || new_kernel.cols() != n_new ||
1621 cross_old_new.rows() != n_old || cross_old_new.cols() != n_new ||
1622 old_basis.leftSingularVectors().rows() != n_old ||
1623 old_basis.leftSingularVectors().cols() != r_old ||
1624 old_basis.singularValues().size() != r_old || r_old <= 0) {
1625 rank_ = 0;
1626 Psi_.resize(std::max<Eigen::Index>(0, n_old + n_new), 0);
1627 Sr_.resize(0);
1628 return false;
1629 }
1630
1631 const Eigen::MatrixXd& U = old_basis.leftSingularVectors();
1632 const Eigen::VectorXd& S = old_basis.singularValues();
1633 const Eigen::MatrixXd C = cross_old_new;
1634 const Eigen::MatrixXd D = 0.5 * (new_kernel + new_kernel.transpose());
1635
1636 Eigen::MatrixXd UtC;
1638 UtC = linalg::trainingProduct(U, C, true);
1639 else
1640 UtC.noalias() = U.transpose() * C;
1641 const Eigen::MatrixXd residual = C - U * UtC;
1642
1643 Eigen::MatrixXd Q(n_old, 0);
1644 if (residual.size() > 0) {
1645 Eigen::BDCSVD<Eigen::MatrixXd> rsvd(residual, Eigen::ComputeThinU);
1646 const Eigen::VectorXd& Rsv = rsvd.singularValues();
1647 Eigen::Index q_rank = 0;
1648 if (Rsv.size() > 0 && Rsv(0) > 0.0) {
1649 const double kernel_scale =
1650 std::max(C.norm(), S.array().square().matrix().norm());
1651 const double tol = std::numeric_limits<double>::epsilon() *
1652 static_cast<double>(
1653 std::max(residual.rows(), residual.cols())) *
1654 kernel_scale;
1655 while (q_rank < Rsv.size() && Rsv(q_rank) > tol)
1656 ++q_rank;
1657 }
1658 if (q_rank > 0) {
1659 Q = rsvd.matrixU().leftCols(q_rank);
1660 Q -= U * (U.transpose() * Q);
1661 Q = Eigen::HouseholderQR<Eigen::MatrixXd>(Q).householderQ() *
1662 Eigen::MatrixXd::Identity(n_old, q_rank);
1663 }
1664 }
1665
1666 const Eigen::Index q = Q.cols();
1667 const Eigen::Index m_small = r_old + q + n_new;
1668 Eigen::MatrixXd projected = Eigen::MatrixXd::Zero(m_small, m_small);
1669 projected.topLeftCorner(r_old, r_old).diagonal() =
1670 S.array().square().matrix();
1671 projected.block(0, r_old + q, r_old, n_new) = UtC;
1672 projected.block(r_old + q, 0, n_new, r_old) = UtC.transpose();
1673 if (q > 0) {
1674 Eigen::MatrixXd QtC;
1676 QtC = linalg::trainingProduct(Q, C, true);
1677 else
1678 QtC.noalias() = Q.transpose() * C;
1679 projected.block(r_old, r_old + q, q, n_new) = QtC;
1680 projected.block(r_old + q, r_old, n_new, q) = QtC.transpose();
1681 }
1682 projected.bottomRightCorner(n_new, n_new) = D;
1683 projected = 0.5 * (projected + projected.transpose()).eval();
1684
1685 Eigen::VectorXd evals_asc;
1686 Eigen::MatrixXd evecs_asc;
1687 // Same dispatch as the full-refactorize paths: distributed across ranks
1688 // when there is more than one, else cuSOLVER above the size floor and
1689 // LAPACK below it. The projected block is near-full-size on
1690 // flat-spectrum kernels, so this eigensolve dominates the per-append
1691 // cost and is the one worth spreading.
1692 // This block is a diagonal bordered by the appended rows, because U
1693 // already diagonalises the old kernel, and an arrowhead has an
1694 // O(k m^2) solver where this dense call is O(m^3). It is not used,
1695 // and the reason is the width: an acquisition appends
1696 // delta_images * (1 + 3 natoms) rows, so k is thirty to sixty rather
1697 // than one or two. gpr::linalg::arrowheadEigen absorbs one border
1698 // column per pass and accumulates the basis with a dense product each
1699 // time, which is O(k m^3) in total and loses to one dense solve as
1700 // soon as k passes a handful: measured at m = 800, 4.84x faster at
1701 // k = 1, 0.56x at k = 8, 0.09x at k = 62.
1702 //
1703 // The structure is still there to be used; successive bordering is
1704 // just the wrong way to use it at this width, and a block
1705 // divide-and-conquer that never forms the accumulated basis densely
1706 // is the right one.
1707 const char* append_driver = "serial_floor";
1708 if (dispatchAllEigenpairs(backend(), projected, evals_asc, evecs_asc,
1709 &append_driver)) {
1710 last_kernel_factorize_driver_ = append_driver;
1711 } else if (fastAllEigenpairs(backend().mpi(), projected, evals_asc,
1712 evecs_asc)) {
1713 fast_kernel_eigensolver_used_ = true;
1714 } else {
1715 Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> es =
1716 timedSymmetricEigen(projected);
1717 if (es.info() != Eigen::Success || es.eigenvalues().size() == 0) {
1718 rank_ = 0;
1719 Psi_.resize(n_old + n_new, 0);
1720 Sr_.resize(0);
1721 return false;
1722 }
1723 evals_asc = es.eigenvalues();
1724 evecs_asc = es.eigenvectors();
1725 gpr::linalg::canonicalizeEigenpairs(evals_asc, evecs_asc);
1726 }
1727 Eigen::VectorXd Snew(m_small);
1728 Eigen::MatrixXd Z(m_small, m_small);
1729 for (Eigen::Index i = 0; i < m_small; ++i) {
1730 const Eigen::Index src = m_small - 1 - i;
1731 Snew(i) = std::sqrt(std::max(0.0, evals_asc(src)));
1732 Z.col(i) = evecs_asc.col(src);
1733 }
1734
1735 rank_ = static_cast<int>(keptSingularRankWithChop(
1736 Snew, dualKernelSingularCutoff(Snew, sv_rtol, sv_abs_tol), sv_chop_tol,
1737 chop_sigma2_));
1739 Sr_ = Snew.head(rank_);
1740
1741 Eigen::MatrixXd P = Eigen::MatrixXd::Zero(n_old + n_new, m_small);
1742 P.block(0, 0, n_old, r_old) = U;
1743 if (q > 0) P.block(0, r_old, n_old, q) = Q;
1744 P.block(n_old, r_old + q, n_new, n_new).setIdentity();
1745 // Near-full rank makes this an O(n^3) product every append. Disjoint
1746 // output columns distribute the work while retaining a replicated basis.
1747 {
1748 const Eigen::MatrixXd Zr = Z.leftCols(rank_);
1749 bool multiplied = false;
1750#ifdef GPR_LINALG_SCALAPACK
1751 auto& state = backend().distributed();
1752 state.initialize();
1753 if (!reproducibleBasis() && state.nprocs() > 1 &&
1754 std::min({P.rows(), P.cols(), Zr.cols()}) >=
1756 multiplied = backend().distributed_gemm_nn(P, Zr, Psi_);
1757 }
1758#endif
1759 if (!multiplied) {
1760 Psi_.resize(P.rows(), Zr.cols());
1761 if (!linalg::tryTrainingProduct(P, Zr, Psi_)) {
1762 auto* gpu = availableGpuEigensolver(backend().mpi());
1763 if (!(gpu != nullptr && gpu->gemmNN(P, Zr, Psi_))) {
1764 Psi_.noalias() = P * Zr;
1765 }
1766 }
1767 }
1768 }
1769 if (rank_ > 0 && old_bordered.rows() == n_old &&
1770 old_bordered.cols() == n_old) {
1771 bordered_kernel_.resize(n_old + n_new, n_old + n_new);
1772 bordered_kernel_.topLeftCorner(n_old, n_old) = old_bordered;
1773 bordered_kernel_.topRightCorner(n_old, n_new) = C;
1774 bordered_kernel_.bottomLeftCorner(n_new, n_old) = C.transpose();
1775 bordered_kernel_.bottomRightCorner(n_new, n_new) = D;
1776 bordered_assembly_error_ = old_asm_error;
1777 }
1778 condition_number_ = rank_ > 0 ? 1.0 : 0.0;
1779 return rank_ > 0;
1780}
Eigen::MatrixXd trainingProduct(ConstProductMatrix a, ConstProductMatrix b, bool transpose_a, bool transpose_b)
Allocating form with a native Eigen product when no device product runs.
bool tryTrainingProduct(ConstProductMatrix a, ConstProductMatrix b, ProductMatrix c, bool transpose_a, bool transpose_b, double alpha, double beta, bool partitioned)
constexpr Eigen::Index kMinDistributedGemmOrder
bool trainingProductConfigured()
A device library or an in-process engine is configured.

◆ factorizeKernelLapackRrr()

bool gpr::StableBasisND::factorizeKernelLapackRrr ( const Eigen::MatrixXd & kernel,
double sv_rtol = 1e-13,
double sv_abs_tol = 0.0,
double sv_chop_tol = 0.0,
bool allow_value_range = false )

Definition at line 1206 of file StableBasis.cpp.

1210{
1211 bordered_kernel_.resize(0, 0);
1212 bordered_assembly_error_ = 0.0;
1213 clearBorderedCache();
1214 ScopedPhaseTimer factorization_timer(PhaseTimers::factorization_seconds);
1216 PhaseTimers::factorization_rows += kernel.rows();
1217 lapack_rrr_value_range_used_ = false;
1218 last_kernel_factorize_driver_ = "unset";
1219 condition_number_ = 0.0;
1220 dim_ = 0;
1221 M_ = static_cast<int>(kernel.rows());
1222 max_degree_ = 0;
1223 gradient_enhanced_ = true;
1224 affine_full_dim_ = 0;
1225 midx_.resize(0, 0);
1226 sqrt_lam_.resize(0);
1227 W_.resize(0, 0);
1228 A_train_.resize(0, 0);
1229 noisy_eigvals_.resize(0);
1230
1231 if (kernel.rows() == 0 || kernel.rows() != kernel.cols()) {
1232 rank_ = 0;
1233 Psi_.resize(kernel.rows(), 0);
1234 Sr_.resize(0);
1235 return kernel.rows() == kernel.cols();
1236 }
1237
1238 Eigen::MatrixXd sym = 0.5 * (kernel + kernel.transpose());
1239 bordered_assembly_error_ = kernelAssemblyErrorBound(kernel, sym);
1240 Eigen::VectorXd evals_asc;
1241 Eigen::MatrixXd evecs_asc;
1242 bool used_cached_spectrum = false;
1243 const Eigen::Index cached_n = cached_spectrum_matrix_.rows();
1244 if (cached_n > 0 && cached_n < sym.rows() &&
1245 cached_spectrum_evals_.size() == cached_n &&
1246 cached_spectrum_evecs_.rows() == cached_n &&
1247 cached_spectrum_evecs_.cols() == cached_n &&
1248 sym.topLeftCorner(cached_n, cached_n) == cached_spectrum_matrix_ &&
1249 extendSymmetricSpectrum(sym, cached_spectrum_evals_,
1250 cached_spectrum_evecs_, evals_asc, evecs_asc)) {
1251 used_cached_spectrum = true;
1252 ++lapack_rrr_extensions_;
1253 last_kernel_factorize_driver_ = "lapack_rrr_arrowhead";
1254 } else if (cached_n == sym.rows() && cached_spectrum_matrix_ == sym &&
1255 cached_spectrum_evals_.size() == cached_n &&
1256 cached_spectrum_evecs_.cols() == cached_n) {
1257 evals_asc = cached_spectrum_evals_;
1258 evecs_asc = cached_spectrum_evecs_;
1259 used_cached_spectrum = true;
1260 last_kernel_factorize_driver_ = "lapack_rrr_cache";
1261 }
1262 bool used_value_range = false;
1263 // DSYEVR range='V' returns eigenpairs with lambda in (vl, vu]. The HS-SVD
1264 // cutoff keeps singular values S > max(sv_rtol*S0, sv_abs_tol). A
1265 // Gershgorin upper bound S0 <= sqrt(upper_eval) proves that sv_abs_tol is
1266 // the active cutoff here, so vl=sv_abs_tol^2 removes exactly the same tail
1267 // as the full-spectrum path. standardChop needs the tail shape and keeps
1268 // the full-spectrum driver.
1269 if (!used_cached_spectrum && allow_value_range && sv_chop_tol <= 0.0 &&
1270 sv_abs_tol > 0.0) {
1271 const double upper_eval = symmetricEigenUpperBound(sym);
1272 const double upper_singular = std::sqrt(std::max(0.0, upper_eval));
1273 if (std::isfinite(upper_singular) &&
1274 sv_abs_tol >= sv_rtol * upper_singular &&
1275 fastEigenpairsAbove(backend().mpi(), sym, sv_abs_tol * sv_abs_tol,
1276 evals_asc, evecs_asc,
1277 &last_kernel_factorize_driver_)) {
1278 used_value_range = true;
1279 }
1280 }
1281 if (!used_cached_spectrum && !used_value_range &&
1282 !fastAllEigenpairs(backend().mpi(), sym, evals_asc, evecs_asc,
1283 &last_kernel_factorize_driver_)) {
1284 rank_ = 0;
1285 Psi_.resize(kernel.rows(), 0);
1286 Sr_.resize(0);
1287 return false;
1288 }
1289 if (evals_asc.size() == 0) {
1290 rank_ = 0;
1291 Psi_.resize(kernel.rows(), 0);
1292 Sr_.resize(0);
1293 lapack_rrr_value_range_used_ = used_value_range;
1294 return true;
1295 }
1296 if (!used_cached_spectrum && !used_value_range) ++lapack_rrr_full_solves_;
1297 // A partial value-range spectrum is not a basis the next border can
1298 // extend. The full spectrum is the one DSYEVR would return again.
1299 if (!used_value_range && evals_asc.size() == sym.rows() &&
1300 evecs_asc.cols() >= sym.rows()) {
1301 cached_spectrum_matrix_ = sym;
1302 cached_spectrum_evals_ = evals_asc;
1303 cached_spectrum_evecs_ = evecs_asc.leftCols(sym.rows());
1304 }
1305
1306 const Eigen::Index n = evals_asc.size();
1307 Eigen::VectorXd S(n);
1308 for (Eigen::Index i = 0; i < n; ++i) {
1309 const Eigen::Index src = n - 1 - i;
1310 S(i) = std::sqrt(std::max(0.0, evals_asc(src)));
1311 }
1312
1313 rank_ = static_cast<int>(keptSingularRankWithChop(
1314 S, dualKernelSingularCutoff(S, sv_rtol, sv_abs_tol), sv_chop_tol,
1315 chop_sigma2_));
1317 Sr_ = S.head(rank_);
1318 Psi_.resize(kernel.rows(), rank_);
1319 for (Eigen::Index i = 0; i < rank_; ++i) {
1320 const Eigen::Index src = n - 1 - i;
1321 Psi_.col(i) = evecs_asc.col(src);
1322 }
1323 bordered_kernel_ = std::move(sym);
1324 lapack_rrr_value_range_used_ = used_value_range;
1325 condition_number_ = rank_ > 0 ? 1.0 : 0.0;
1326 return true;
1327}
bool extendSymmetricSpectrum(const Eigen::Ref< const Eigen::MatrixXd > &grown, const Eigen::Ref< const Eigen::VectorXd > &diagonal, const Eigen::Ref< const Eigen::MatrixXd > &basis, Eigen::VectorXd &evals, Eigen::MatrixXd &evecs)

◆ factorizeKernelRandomized()

void gpr::StableBasisND::factorizeKernelRandomized ( const Eigen::MatrixXd & kernel,
int sketch_size,
int n_power_iter = 2,
double sv_rtol = 1e-13,
double sv_abs_tol = 0.0,
double sv_chop_tol = 0.0 )

Definition at line 1466 of file StableBasis.cpp.

1470{
1471 bordered_kernel_.resize(0, 0);
1472 bordered_assembly_error_ = 0.0;
1473 clearBorderedCache();
1474 lapack_rrr_value_range_used_ = false;
1475 condition_number_ = 0.0;
1476 if (sketch_size <= 0) {
1477 factorizeKernel(kernel, sv_rtol, sv_abs_tol, sv_chop_tol);
1478 return;
1479 }
1480
1481 dim_ = 0;
1482 M_ = static_cast<int>(kernel.rows());
1483 max_degree_ = 0;
1484 gradient_enhanced_ = true;
1485 affine_full_dim_ = 0;
1486 midx_.resize(0, 0);
1487 sqrt_lam_.resize(0);
1488 W_.resize(0, 0);
1489 A_train_.resize(0, 0);
1490
1491 if (kernel.rows() == 0 || kernel.rows() != kernel.cols()) {
1492 rank_ = 0;
1493 Psi_.resize(kernel.rows(), 0);
1494 Sr_.resize(0);
1495 return;
1496 }
1497
1498 Eigen::MatrixXd sym = 0.5 * (kernel + kernel.transpose());
1499 bordered_assembly_error_ = kernelAssemblyErrorBound(kernel, sym);
1500 const Eigen::Index n = sym.rows();
1501 Eigen::Index l = std::min<Eigen::Index>(
1502 std::max<Eigen::Index>(1, static_cast<Eigen::Index>(sketch_size)), n);
1503 const int n_power = std::max(0, n_power_iter);
1504
1505 for (;;) {
1506 std::mt19937_64 gen(0x5EED1234ULL);
1507 std::normal_distribution<double> nd(0.0, 1.0);
1508 Eigen::MatrixXd Omega(n, l);
1509 for (Eigen::Index j = 0; j < l; ++j)
1510 for (Eigen::Index i = 0; i < n; ++i)
1511 Omega(i, j) = nd(gen);
1512
1513 Eigen::MatrixXd Y = sym * Omega;
1514 for (int p = 0; p < n_power; ++p) {
1515 const Eigen::MatrixXd Qp =
1516 Eigen::HouseholderQR<Eigen::MatrixXd>(Y).householderQ() *
1517 Eigen::MatrixXd::Identity(n, l);
1518 Y = sym * Qp;
1519 }
1520 const Eigen::MatrixXd Q =
1521 Eigen::HouseholderQR<Eigen::MatrixXd>(Y).householderQ() *
1522 Eigen::MatrixXd::Identity(n, l);
1523 Eigen::MatrixXd T = Q.transpose() * sym * Q;
1524 T = 0.5 * (T + T.transpose()).eval();
1525
1526 Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> es =
1527 timedSymmetricEigen(T);
1528 if (es.info() != Eigen::Success || es.eigenvalues().size() == 0) {
1529 rank_ = 0;
1530 Psi_.resize(n, 0);
1531 Sr_.resize(0);
1532 return;
1533 }
1534
1535 const Eigen::VectorXd evals_asc = es.eigenvalues();
1536 const Eigen::MatrixXd evecs_asc = es.eigenvectors();
1537 Eigen::VectorXd S(l);
1538 Eigen::MatrixXd Z(l, l);
1539 for (Eigen::Index i = 0; i < l; ++i) {
1540 const Eigen::Index src = l - 1 - i;
1541 S(i) = std::sqrt(std::max(0.0, evals_asc(src)));
1542 Z.col(i) = evecs_asc.col(src);
1543 }
1544
1545 const Eigen::Index rk = keptSingularRankWithChop(
1546 S, dualKernelSingularCutoff(S, sv_rtol, sv_abs_tol), sv_chop_tol,
1547 chop_sigma2_);
1548 if (rk == l && l < n) {
1549 l = std::min<Eigen::Index>(2 * l, n);
1550 continue;
1551 }
1552
1553 rank_ = static_cast<int>(rk);
1554
1556 Sr_ = S.head(rk);
1557 Psi_ = Q * Z.leftCols(rk);
1558 bordered_kernel_ = std::move(sym);
1559 condition_number_ = rank_ > 0 ? 1.0 : 0.0;
1560 return;
1561 }
1562}
void factorizeKernel(const Eigen::MatrixXd &kernel, double sv_rtol=1e-13, double sv_abs_tol=0.0, double sv_chop_tol=0.0)

◆ factorizeNoisyKernel()

void gpr::StableBasisND::factorizeNoisyKernel ( const Eigen::MatrixXd & noisy_kernel,
double sigma2 )

Definition at line 1360 of file StableBasis.cpp.

1362{
1363 bordered_kernel_.resize(0, 0);
1364 bordered_assembly_error_ = 0.0;
1365 clearBorderedCache();
1366 ScopedPhaseTimer factorization_timer(PhaseTimers::factorization_seconds);
1368 PhaseTimers::factorization_rows += noisy_kernel.rows();
1369 lapack_rrr_value_range_used_ = false;
1370 condition_number_ = 0.0;
1371 dim_ = 0;
1372 M_ = static_cast<int>(noisy_kernel.rows());
1373 max_degree_ = 0;
1374 gradient_enhanced_ = true;
1375 affine_full_dim_ = 0;
1376 midx_.resize(0, 0);
1377 sqrt_lam_.resize(0);
1378 W_.resize(0, 0);
1379 A_train_.resize(0, 0);
1380 noisy_eigvals_.resize(0);
1381
1382 if (noisy_kernel.rows() == 0 ||
1383 noisy_kernel.rows() != noisy_kernel.cols()) {
1384 rank_ = 0;
1385 Psi_.resize(noisy_kernel.rows(), 0);
1386 Sr_.resize(0);
1387 return;
1388 }
1389
1390 const Eigen::MatrixXd sym = 0.5 * (noisy_kernel + noisy_kernel.transpose());
1391 // cuSOLVER syevd is divide-and-conquer -- the GPU equivalent of Eigen's
1392 // SelfAdjointEigenSolver -- so it is the faithful accelerator for this
1393 // (non-RRR) path. The flag's MRRR algorithm choice is preserved on the
1394 // CPU fallback below.
1395 auto* cusolver = availableGpuEigensolver(backend().mpi());
1396 Eigen::VectorXd evals_gpu;
1397 Eigen::MatrixXd evecs_gpu;
1398 if (cusolver && cusolver->allEigenpairs(sym, evals_gpu, evecs_gpu) &&
1399 evals_gpu.size() > 0) {
1400 finalizeNoisyKernel(evals_gpu, evecs_gpu, sigma2, rank_, Psi_, Sr_,
1401 noisy_eigvals_, condition_number_);
1402 return;
1403 }
1404 Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> es =
1405 timedSymmetricEigen(sym);
1406 if (es.info() != Eigen::Success || es.eigenvalues().size() == 0) {
1407 rank_ = 0;
1408 Psi_.resize(noisy_kernel.rows(), 0);
1409 Sr_.resize(0);
1410 return;
1411 }
1412 finalizeNoisyKernel(es.eigenvalues(), es.eigenvectors(), sigma2, rank_,
1413 Psi_, Sr_, noisy_eigvals_, condition_number_);
1414}

◆ factorizeNoisyKernelLapackRrr()

bool gpr::StableBasisND::factorizeNoisyKernelLapackRrr ( const Eigen::MatrixXd & noisy_kernel,
double sigma2 )

Definition at line 1416 of file StableBasis.cpp.

1418{
1419 bordered_kernel_.resize(0, 0);
1420 bordered_assembly_error_ = 0.0;
1421 clearBorderedCache();
1422 ScopedPhaseTimer factorization_timer(PhaseTimers::factorization_seconds);
1424 PhaseTimers::factorization_rows += noisy_kernel.rows();
1425 lapack_rrr_value_range_used_ = false;
1426 condition_number_ = 0.0;
1427 dim_ = 0;
1428 M_ = static_cast<int>(noisy_kernel.rows());
1429 max_degree_ = 0;
1430 gradient_enhanced_ = true;
1431 affine_full_dim_ = 0;
1432 midx_.resize(0, 0);
1433 sqrt_lam_.resize(0);
1434 W_.resize(0, 0);
1435 A_train_.resize(0, 0);
1436 noisy_eigvals_.resize(0);
1437
1438 if (noisy_kernel.rows() == 0 ||
1439 noisy_kernel.rows() != noisy_kernel.cols()) {
1440 rank_ = 0;
1441 Psi_.resize(noisy_kernel.rows(), 0);
1442 Sr_.resize(0);
1443 return noisy_kernel.rows() == noisy_kernel.cols();
1444 }
1445
1446 const Eigen::MatrixXd sym = 0.5 * (noisy_kernel + noisy_kernel.transpose());
1447 Eigen::VectorXd evals_asc;
1448 Eigen::MatrixXd evecs_asc;
1449 if (!fastAllEigenpairs(backend().mpi(), sym, evals_asc, evecs_asc)) {
1450 rank_ = 0;
1451 Psi_.resize(noisy_kernel.rows(), 0);
1452 Sr_.resize(0);
1453 return false;
1454 }
1455 if (evals_asc.size() == 0) {
1456 rank_ = 0;
1457 Psi_.resize(noisy_kernel.rows(), 0);
1458 Sr_.resize(0);
1459 return true;
1460 }
1461 finalizeNoisyKernel(evals_asc, evecs_asc, sigma2, rank_, Psi_, Sr_,
1462 noisy_eigvals_, condition_number_);
1463 return true;
1464}

◆ floorCertifiedSchurDiagonal()

StableBasisND::SchurFloorReport gpr::StableBasisND::floorCertifiedSchurDiagonal ( const Eigen::MatrixXd & cross,
const Eigen::VectorXd & prior,
double sigma2,
Eigen::VectorXd & value,
const std::vector< char > * skip = nullptr ) const

value(j) is a computed Schur diagonal prior(j) - cross_j^T (K + sigma2 I)^(-1) cross_j. Nonnegative entries are untouched; no entry is left negative or NaN. A negative entry is replaced by the smallest nonnegative value of the outward-rounded bordered enclosure of that same quantity: 0 where the enclosure contains zero (lower <= 0 <= upper, counted as floored), and the lower endpoint where it is entirely positive (counted as raised). Where the enclosure is entirely negative the entry becomes +inf and counts as proven negative. A NaN or -inf entry, and a negative one without an enclosure, becomes +inf and counts as uncertified. skip, when given, has one flag per entry. A flagged entry has already been replaced by another certified formula (the latent training-row variance), so it is neither floored nor counted: the counts describe the entries that remain in value.

Definition at line 4842 of file StableBasis.cpp.

4845{
4846 if (cross.cols() != value.size() || prior.size() != value.size() ||
4847 cross.rows() != Psi_.rows() ||
4848 (skip && static_cast<Eigen::Index>(skip->size()) != value.size()))
4849 throw std::invalid_argument(
4850 "Schur diagonal certification needs one cross column and one "
4851 "prior entry per value");
4852 const double inf = std::numeric_limits<double>::infinity();
4853 SchurFloorReport report;
4854 std::vector<Eigen::Index> negative;
4855 for (Eigen::Index i = 0; i < value.size(); ++i) {
4856 if (skip && (*skip)[static_cast<std::size_t>(i)]) continue;
4857 if (std::isnan(value(i)) || value(i) == -inf) {
4858 value(i) = inf;
4859 ++report.uncertified;
4860 } else if (value(i) < 0.0) {
4861 if (!cross.col(i).allFinite() || !std::isfinite(prior(i))) {
4862 value(i) = inf;
4863 ++report.uncertified;
4864 } else {
4865 negative.push_back(i);
4866 }
4867 }
4868 }
4869 if (!negative.empty()) {
4870 std::vector<BorderedVarianceInterval> intervals;
4871 bool enclosed = false;
4872 if (supportsBorderedVarianceInterval() && std::isfinite(sigma2) &&
4873 sigma2 >= 0.0) {
4874 Eigen::MatrixXd rhs(cross.rows(),
4875 static_cast<Eigen::Index>(negative.size()));
4876 Eigen::VectorXd prior_subset(rhs.cols());
4877 for (Eigen::Index k = 0; k < rhs.cols(); ++k) {
4878 rhs.col(k) = cross.col(negative[static_cast<std::size_t>(k)]);
4879 prior_subset(k) = prior(negative[static_cast<std::size_t>(k)]);
4880 }
4881 try {
4883 rhs, prior_subset, sigma2,
4885 enclosed = intervals.size() == negative.size();
4886 } catch (const std::runtime_error&) {
4887 enclosed = false;
4888 }
4889 }
4890 for (std::size_t k = 0; k < negative.size(); ++k) {
4891 double& entry = value(negative[k]);
4892 if (!enclosed) {
4893 entry = inf;
4894 ++report.uncertified;
4895 } else if (intervals[k].upper < 0.0) {
4896 entry = inf;
4897 ++report.proven_negative;
4898 } else if (intervals[k].lower <= 0.0) {
4899 // The enclosure contains zero, so the true value may be zero
4900 // and the negative computed value is roundoff.
4901 entry = 0.0;
4902 ++report.floored;
4903 } else {
4904 // The enclosure is wholly positive: binary64 cancellation put
4905 // the computed value below a true value of at least lower.
4906 entry = intervals[k].lower;
4907 ++report.raised;
4908 }
4909 }
4910 }
4911 recordSchurFloor(report);
4912 return report;
4913}
bool supportsBorderedVarianceInterval() const noexcept
std::vector< BorderedVarianceInterval > noisyBorderedVarianceIntervals(const Eigen::MatrixXd &rhs, const Eigen::VectorXd &prior_diag, double sigma2) const
What floorCertifiedSchurDiagonal did to a diagonal.

◆ floorLatentVariance()

double gpr::StableBasisND::floorLatentVariance ( double latent,
double error_bound,
SchurFloorReport * report )
staticnoexcept

Floors a computed latent variance. A nonnegative value, +inf included, is returned as is. A negative value whose error bound reaches 0 is roundoff and becomes 0. One whose bound stays negative is proven negative and becomes +inf. A NaN or -inf value, or a negative one whose bound is NaN, infinite or negative, has no certificate: it becomes +inf and counts as uncertified.

Definition at line 4964 of file StableBasis.cpp.

4966{
4967 if (latent >= 0.0) return latent;
4968 const double inf = std::numeric_limits<double>::infinity();
4969 SchurFloorReport local;
4970 double result = inf;
4971 if (!std::isfinite(latent) || !std::isfinite(error_bound) ||
4972 !(error_bound >= 0.0))
4973 ++local.uncertified;
4974 else if (latent + error_bound >= 0.0) {
4975 ++local.floored;
4976 result = 0.0;
4977 } else
4978 ++local.proven_negative;
4979 recordSchurFloor(local);
4980 if (report) {
4981 report->floored += local.floored;
4982 report->proven_negative += local.proven_negative;
4983 report->uncertified += local.uncertified;
4984 }
4985 return result;
4986}

◆ gradedModeCountExceedsLimit()

bool gpr::StableBasisND::gradedModeCountExceedsLimit ( int dim,
int max_degree,
Eigen::Index limit )
static

Definition at line 960 of file StableBasis.cpp.

962{
963 if (dim < 0 || max_degree < 0 || limit < 0) return true;
964 if (dim == 0 || max_degree == 0) return 1 > limit;
965
966 const int k = std::min(dim, max_degree);
967 const int n = dim + max_degree;
968 long double count = 1.0L;
969 const long double cap = static_cast<long double>(limit);
970 for (int i = 1; i <= k; ++i) {
971 count *= static_cast<long double>(n - k + i);
972 count /= static_cast<long double>(i);
973 if (count > cap) return true;
974 }
975 return count > cap;
976}

◆ hasCrossCovariance()

bool gpr::StableBasisND::hasCrossCovariance ( ) const
inline

Definition at line 936 of file StableBasis.h.

937 {
938 return A_train_.size() > 0;
939 }

◆ hasNoisyEigenvalues()

bool gpr::StableBasisND::hasNoisyEigenvalues ( ) const
inline

Definition at line 964 of file StableBasis.h.

965 {
966 return noisy_eigvals_.size() == Sr_.size() && noisy_eigvals_.size() > 0;
967 }

◆ lapackRrrExtensionsForTesting()

int gpr::StableBasisND::lapackRrrExtensionsForTesting ( ) const
inlinenodiscardnoexcept

Definition at line 842 of file StableBasis.h.

843 {
844 return lapack_rrr_extensions_;
845 }

◆ lapackRrrFullSolvesForTesting()

int gpr::StableBasisND::lapackRrrFullSolvesForTesting ( ) const
inlinenodiscardnoexcept

Full DSYEVR calls. A repeated kernel and a bordered extension of a cached spectrum do not increment this.

Definition at line 838 of file StableBasis.h.

839 {
840 return lapack_rrr_full_solves_;
841 }

◆ lastKernelFactorizeDriver()

const char * gpr::StableBasisND::lastKernelFactorizeDriver ( ) const
inlinenodiscardnoexcept

Definition at line 832 of file StableBasis.h.

833 {
834 return last_kernel_factorize_driver_;
835 }

◆ latentVarianceOperationDepthForTesting()

long long gpr::StableBasisND::latentVarianceOperationDepthForTesting ( Eigen::Index rank)
staticnodiscardnoexcept

Operations a term of the training-row latent variance passes through, which trainingRowLatentErrorBound scales the unit roundoff by.

Definition at line 4794 of file StableBasis.cpp.

4796{
4797 return latentVarianceOperationDepth(rank);
4798}

◆ leaveOneOutNegativeLogPredictiveDensity()

double gpr::StableBasisND::leaveOneOutNegativeLogPredictiveDensity ( const Eigen::VectorXd & y,
double sigma2 ) const

Definition at line 3974 of file StableBasis.cpp.

3976{
3977 if (y.size() != Psi_.rows() || !(sigma2 > 0.0)) {
3978 return std::numeric_limits<double>::quiet_NaN();
3979 }
3980
3981 const Eigen::VectorXd alpha = solveNoisy(y, sigma2);
3982 const Eigen::VectorXd inv_diag = noisyInverseDiagonal(sigma2);
3983 if (alpha.size() != y.size() || inv_diag.size() != y.size()) {
3984 return std::numeric_limits<double>::quiet_NaN();
3985 }
3986
3987 double nlp = 0.0;
3988 const double log_two_pi = std::log(2.0 * std::acos(-1.0));
3989 for (Eigen::Index i = 0; i < y.size(); ++i) {
3990 const double q = inv_diag(i);
3991 if (!(q > 0.0) || !std::isfinite(q) || !std::isfinite(alpha(i))) {
3992 return std::numeric_limits<double>::quiet_NaN();
3993 }
3994 nlp += 0.5 * (log_two_pi - std::log(q) + alpha(i) * alpha(i) / q);
3995 }
3996 return nlp;
3997}

◆ leaveOneOutNegativeLogPredictiveDensityDirectionalDerivative()

double gpr::StableBasisND::leaveOneOutNegativeLogPredictiveDensityDirectionalDerivative ( const Eigen::VectorXd & y,
double sigma2,
const Eigen::MatrixXd & dK ) const

Definition at line 4106 of file StableBasis.cpp.

4108{
4109 if (y.size() != Psi_.rows() || !(sigma2 > 0.0) ||
4110 dK.rows() != Psi_.rows() || dK.cols() != Psi_.rows()) {
4111 return std::numeric_limits<double>::quiet_NaN();
4112 }
4113
4114 const Eigen::VectorXd alpha = solveNoisy(y, sigma2);
4115 const Eigen::VectorXd inv_diag = noisyInverseDiagonal(sigma2);
4116 const Eigen::VectorXd dalpha = -solveNoisy(dK * alpha, sigma2);
4117 const Eigen::VectorXd dq = -noisyInverseSandwichDiagonal(dK, sigma2);
4118 if (alpha.size() != y.size() || inv_diag.size() != y.size() ||
4119 dalpha.size() != y.size() || dq.size() != y.size()) {
4120 return std::numeric_limits<double>::quiet_NaN();
4121 }
4122
4123 double derivative = 0.0;
4124 for (Eigen::Index i = 0; i < y.size(); ++i) {
4125 const double q = inv_diag(i);
4126 if (!(q > 0.0) || !std::isfinite(q) || !std::isfinite(alpha(i)) ||
4127 !std::isfinite(dalpha(i)) || !std::isfinite(dq(i))) {
4128 return std::numeric_limits<double>::quiet_NaN();
4129 }
4130 derivative +=
4131 0.5 * ((-1.0 / q - alpha(i) * alpha(i) / (q * q)) * dq(i) +
4132 2.0 * alpha(i) * dalpha(i) / q);
4133 }
4134 return derivative;
4135}
Eigen::VectorXd noisyInverseSandwichDiagonal(const Eigen::MatrixXd &dK, double sigma2) const

◆ leaveOneOutNegativeLogPredictiveDensityGrouped()

double gpr::StableBasisND::leaveOneOutNegativeLogPredictiveDensityGrouped ( const Eigen::VectorXd & y,
double sigma2,
const std::vector< std::vector< Eigen::Index > > & groups ) const

Definition at line 4156 of file StableBasis.cpp.

4159{
4160 if (y.size() != Psi_.rows() || !(sigma2 > 0.0)) {
4161 return std::numeric_limits<double>::quiet_NaN();
4162 }
4163 const Eigen::VectorXd alpha = solveNoisy(y, sigma2);
4164 if (alpha.size() != y.size()) {
4165 return std::numeric_limits<double>::quiet_NaN();
4166 }
4167 // Block-diagonal of (K+sigma2 I)^-1 WITHOUT forming the dense n x n
4168 // inverse. noisyInverse() = q I + Psi diag(d) Psi^T, d = 1/mu - q;
4169 // q = 0 for a full basis and 1/s otherwise.
4170 // grouped LOO needs only the b x b diagonal blocks Cinv_BB, so build each
4171 // directly from the b x r rows of Psi: Cinv_BB = q I_b + Psi_B diag(d)
4172 // Psi_B^T. This is O(sum_B b^2 r) with no O(n^2 r) inverse assembly and no
4173 // O(n^2) storage.
4174 const double sig_f = conditionFlooredSigma2(Sr_, sigma2, Psi_.rows());
4175 const Eigen::Index rrank = Sr_.size();
4176 if (Psi_.rows() != y.size() || Psi_.cols() != rrank || !(sig_f > 0.0)) {
4177 return std::numeric_limits<double>::quiet_NaN();
4178 }
4179 const Eigen::ArrayXd mu =
4180 hasNoisyEigenvalues() ? Eigen::ArrayXd(noisy_eigvals_.array())
4181 : Eigen::ArrayXd(Sr_.array().square() + sig_f);
4182 // The complement weight is the one solveNoisy gives alpha, so the block
4183 // inverse and the weights describe one and the same (K + sigma2 I)^-1.
4184 const double q = complementWeight(sig_f);
4185 const Eigen::ArrayXd d = mu.inverse() - q;
4186 const double log_two_pi = std::log(2.0 * std::acos(-1.0));
4187 double nlp = 0.0;
4188 for (const auto& g: groups) {
4189 const Eigen::Index b = static_cast<Eigen::Index>(g.size());
4190 if (b <= 0) continue;
4191 Eigen::MatrixXd PB(b, rrank); // Psi rows for this block
4192 Eigen::VectorXd aB(b);
4193 for (Eigen::Index r = 0; r < b; ++r) {
4194 const Eigen::Index idx = g[static_cast<size_t>(r)];
4195 aB(r) = alpha(idx);
4196 PB.row(r) = Psi_.row(idx);
4197 }
4198 Eigen::MatrixXd M =
4199 (PB * d.matrix().asDiagonal()) * PB.transpose(); // low-rank part
4200 M.diagonal().array() += q;
4201 // Condition-floor ridge: a redundant geometry block makes Cinv_BB
4202 // near-singular so its inverse (the LOO predictive covariance) blows up
4203 // and the score/gradient go pathological (the 19/24 divergence). Floor
4204 // the smallest eigenvalue at max_diag*sqrt(eps) so cond(M) <=
4205 // 1/sqrt(eps).
4206 const double ridge =
4207 std::sqrt(std::numeric_limits<double>::epsilon()) *
4208 std::max(1e-300, M.diagonal().cwiseAbs().maxCoeff());
4209 M.diagonal().array() += ridge;
4210 const Eigen::LDLT<Eigen::MatrixXd> ldlt(M);
4211 if (ldlt.info() != Eigen::Success)
4212 return std::numeric_limits<double>::quiet_NaN();
4213 const Eigen::VectorXd Sa = ldlt.solve(aB); // (Cinv_BB)^-1 alpha_B
4214 const double logdetM = ldlt.vectorD().array().abs().log().sum();
4215 const double quad = aB.dot(Sa);
4216 if (!std::isfinite(logdetM) || !std::isfinite(quad))
4217 return std::numeric_limits<double>::quiet_NaN();
4218 nlp += 0.5 * (static_cast<double>(b) * log_two_pi - logdetM + quad);
4219 }
4220 return nlp;
4221}
bool hasNoisyEigenvalues() const
double complementWeight(double sigma2) const noexcept

◆ leaveOneOutNegativeLogPredictiveDensityGroupedDirectionalDerivative()

double gpr::StableBasisND::leaveOneOutNegativeLogPredictiveDensityGroupedDirectionalDerivative ( const Eigen::VectorXd & y,
double sigma2,
const Eigen::MatrixXd & dK,
const std::vector< std::vector< Eigen::Index > > & groups ) const

Definition at line 4223 of file StableBasis.cpp.

4227{
4228 if (y.size() != Psi_.rows() || !(sigma2 > 0.0) ||
4229 dK.rows() != Psi_.rows() || dK.cols() != Psi_.rows()) {
4230 return std::numeric_limits<double>::quiet_NaN();
4231 }
4232 const double sig_f = conditionFlooredSigma2(Sr_, sigma2, Psi_.rows());
4233 const Eigen::Index rrank = Sr_.size();
4234 const Eigen::VectorXd alpha = solveNoisy(y, sigma2);
4235 if (alpha.size() != y.size() || Psi_.rows() != y.size() ||
4236 Psi_.cols() != rrank || !(sig_f > 0.0)) {
4237 return std::numeric_limits<double>::quiet_NaN();
4238 }
4239 // The value is the objective of the truncated kernel K_r = P S^2 P^T
4240 // (P = Psi): a dropped direction carries no kernel variance at any
4241 // theta, so the kernel derivative it sees is dK with its dropped-dropped
4242 // block removed,
4243 // dK_r = dK - Q dK Q = R P^T + P R^T + P G P^T,
4244 // with G = P^T dK P (r x r) and R = dK P - P G = Q dK P (n x r), the
4245 // coupling of the retained modes into the complement. R is formed as a
4246 // residual, so a structurally null direction contributes rounding of dK
4247 // and not a q-weighted copy of it.
4248 //
4249 // Cinv = q I + P D P^T with D = 1/mu - q, so Cinv P = P diag(1/mu) and
4250 // Cinv R = q R (P^T R = 0). The sandwich S = Cinv dK_r Cinv is then
4251 // S = P Minv G Minv P^T + q (R Minv P^T + P Minv R^T),
4252 // whose block S_BB follows from the b x r rows of P and R. The dense
4253 // form q^2 dK_BB + q[(dK P)_B D P_B^T + sym] + P_B D G D P_B^T is equal
4254 // in exact arithmetic and cancels q^2 |dK| against itself, which at
4255 // q = 1/sigma2 and a collapsed length scale leaves no digits.
4256 const double q = complementWeight(sig_f);
4257 const Eigen::ArrayXd mu =
4258 hasNoisyEigenvalues() ? Eigen::ArrayXd(noisy_eigvals_.array())
4259 : Eigen::ArrayXd(Sr_.array().square() + sig_f);
4260 const Eigen::VectorXd minv = mu.inverse().matrix();
4261 const Eigen::VectorXd dvec = (mu.inverse() - q).matrix();
4262 const Eigen::MatrixXd dKP = dK * Psi_; // n x r
4263 const Eigen::MatrixXd G = Psi_.transpose() * dKP; // r x r
4264 const Eigen::MatrixXd R = dKP - Psi_ * G; // n x r
4265 // dK_r alpha = R z + P (G z + R^T alpha), z = P^T alpha.
4266 const Eigen::VectorXd z = Psi_.transpose() * alpha;
4267 const Eigen::VectorXd u = R * z + Psi_ * (G * z + R.transpose() * alpha);
4268 const Eigen::VectorXd dalpha = -solveNoisy(u, sigma2);
4269 if (dalpha.size() != y.size()) {
4270 return std::numeric_limits<double>::quiet_NaN();
4271 }
4272 const Eigen::MatrixXd MinvGMinv =
4273 minv.asDiagonal() * G * minv.asDiagonal(); // r x r
4274 double deriv = 0.0;
4275 for (const auto& g: groups) {
4276 const Eigen::Index b = static_cast<Eigen::Index>(g.size());
4277 if (b <= 0) continue;
4278 Eigen::MatrixXd PB(b, rrank), RB(b, rrank);
4279 Eigen::VectorXd aB(b), daB(b);
4280 for (Eigen::Index r = 0; r < b; ++r) {
4281 const Eigen::Index gr = g[static_cast<size_t>(r)];
4282 aB(r) = alpha(gr);
4283 daB(r) = dalpha(gr);
4284 PB.row(r) = Psi_.row(gr);
4285 RB.row(r) = R.row(gr);
4286 }
4287 Eigen::MatrixXd M = (PB * dvec.asDiagonal()) * PB.transpose();
4288 M.diagonal().array() += q; // Cinv_BB
4289 const Eigen::MatrixXd PBMinv = PB * minv.asDiagonal(); // b x r
4290 const Eigen::MatrixXd cross = RB * PBMinv.transpose(); // b x b
4291 const Eigen::MatrixXd dM =
4292 -(PB * MinvGMinv * PB.transpose() +
4293 q * (cross + cross.transpose())); // = -S_BB
4294 // Same condition-floor ridge as the value (treated as a constant in
4295 // theta -- the ridge is O(sqrt(eps)) so its dtheta term is negligible).
4296 const double ridge =
4297 std::sqrt(std::numeric_limits<double>::epsilon()) *
4298 std::max(1e-300, M.diagonal().cwiseAbs().maxCoeff());
4299 M.diagonal().array() += ridge;
4300 const Eigen::LDLT<Eigen::MatrixXd> ldlt(M);
4301 if (ldlt.info() != Eigen::Success)
4302 return std::numeric_limits<double>::quiet_NaN();
4303 const Eigen::MatrixXd Sig = ldlt.solve(Eigen::MatrixXd::Identity(b, b));
4304 const Eigen::VectorXd Sa = Sig * aB; // Sigma alpha_B
4305 // d(-logdet M) = -tr(Sigma dM)
4306 const double dlogdet = -(Sig * dM).trace();
4307 // d(alpha_B^T Sigma alpha_B) = 2 alpha_B^T Sigma dalpha_B
4308 // - (Sigma alpha_B)^T dM (Sigma alpha_B)
4309 const double dquad = 2.0 * Sa.dot(daB) - Sa.dot(dM * Sa);
4310 if (!std::isfinite(dlogdet) || !std::isfinite(dquad))
4311 return std::numeric_limits<double>::quiet_NaN();
4312 deriv += 0.5 * (dlogdet + dquad);
4313 }
4314 return deriv;
4315}
@ z
Definition Enums.h:28

◆ leftSingularVectors()

const Eigen::MatrixXd & gpr::StableBasisND::leftSingularVectors ( ) const
inline

Definition at line 950 of file StableBasis.h.

951 {
952 return Psi_;
953 }

◆ liftFromDeflatedSubspace()

void gpr::StableBasisND::liftFromDeflatedSubspace ( Eigen::Index full_rows,
Eigen::MatrixXd lifted_psi,
const detail::RigidDeflationState & deflation,
double extra_assembly_error = 0.0 )

Definition at line 1564 of file StableBasis.cpp.

1567{
1568 M_ = static_cast<int>(full_rows);
1569 Psi_ = std::move(lifted_psi);
1570 const Eigen::Index expected_deflated = deflation.deflated_rows;
1571 const bool has_deflated_bordered =
1572 deflation.active && deflation.full_rows == full_rows &&
1573 bordered_kernel_.rows() == expected_deflated &&
1574 bordered_kernel_.cols() == expected_deflated;
1575 clearBorderedCache();
1576 if (has_deflated_bordered) {
1577 if (extra_assembly_error > 0.0 && std::isfinite(extra_assembly_error)) {
1578 bordered_assembly_error_ += extra_assembly_error;
1579 }
1580 bordered_deflation_ =
1581 std::make_shared<detail::RigidDeflationState>(deflation);
1582 } else {
1583 bordered_kernel_.resize(0, 0);
1584 bordered_assembly_error_ = 0.0;
1585 }
1586}

◆ logDetNoisy()

double gpr::StableBasisND::logDetNoisy ( double sigma2) const

Definition at line 4317 of file StableBasis.cpp.

4318{
4319 sigma2 = conditionFlooredSigma2(Sr_, sigma2, Psi_.rows());
4320 // eigenvalues of K+sigma2 I: S_i^2+sigma2 (i<rank), sigma2 (the rest).
4321 // The noisy-objective path stores mu_i = eig(K+sigma2 I) directly (no mode
4322 // dropped, rank == nobs), so sum log(mu_i) is the exact log-determinant.
4323 const Eigen::Index nobs = Psi_.rows();
4324 if (hasNoisyEigenvalues()) return noisy_eigvals_.array().log().sum();
4325 double ld = (Sr_.array().square() + sigma2).log().sum();
4326 ld += static_cast<double>(nobs - rank_) * std::log(sigma2);
4327 return ld;
4328}

◆ noisyBorderedVarianceIntervals() [1/2]

std::vector< BorderedVarianceInterval > gpr::StableBasisND::noisyBorderedVarianceIntervals ( const Eigen::MatrixXd & rhs,
const Eigen::VectorXd & prior_diag,
double sigma2 ) const

Two-sided variational Schur variance intervals [lower, upper] for s_j = prior_diag(j) - rhs_j^T (K + sigma2 I)^(-1) rhs_j. Requires a stored kernel and a strictly positive certified minimum eigenvalue mu_min of M = K + sigma2 I at the condition-floored noise. The default entry point clamps a negative lower endpoint to zero when the upper endpoint is nonnegative and throws std::runtime_error when the upper endpoint is negative or M cannot be certified. sigma2 is floored through conditionFlooredNoise, the noise the mean, log-determinant and LOO routes invert, so M is the matrix the trained factor used. Endpoints are rounded outward to binary64.

Definition at line 3701 of file StableBasis.cpp.

3704{
3705 return noisyBorderedVarianceIntervals(rhs, prior_diag, sigma2,
3707}

◆ noisyBorderedVarianceIntervals() [2/2]

std::vector< BorderedVarianceInterval > gpr::StableBasisND::noisyBorderedVarianceIntervals ( const Eigen::MatrixXd & rhs,
const Eigen::VectorXd & prior_diag,
double sigma2,
BorderedSchurSign sign ) const

Same enclosure. PreserveSigned keeps a negative Schur value.

Definition at line 3710 of file StableBasis.cpp.

3714{
3715 if (rhs.rows() != Psi_.rows() || rhs.cols() != prior_diag.size() ||
3716 Psi_.cols() != Sr_.size() || !(sigma2 >= 0.0) ||
3717 !std::isfinite(sigma2) || !rhs.allFinite() || !prior_diag.allFinite()) {
3718 throw BorderedVarianceError(
3719 "bordered variance inputs do not match the stable basis");
3720 }
3721 // The interval encloses the posterior of the operator the trained factor
3722 // inverts: mean, logdet and LOO all floor sigma2 through
3723 // conditionFlooredSigma2, so a raw sigma2 below the floor would certify
3724 // (or refuse) a different matrix K + sigma2 I than the one trained on.
3725 sigma2 = conditionFlooredSigma2(Sr_, sigma2, Psi_.rows());
3726 for (Eigen::Index i = 0; i < prior_diag.size(); ++i) {
3727 if (!(prior_diag(i) >= 0.0)) {
3728 throw BorderedVarianceError(
3729 "the bordered covariance is not positive semidefinite");
3730 }
3731 }
3732 std::vector<BorderedVarianceInterval> intervals(
3733 static_cast<std::size_t>(rhs.cols()));
3734 if (rhs.cols() == 0) return intervals;
3735
3736 const auto [factor, rm_cache] = ensureBorderedFactorAndRm(sigma2);
3737 sigma2 = rm_cache->sigma2;
3738
3739 using Extended = gpr::extended::WorkingReal;
3740 using ExtendedVector = Eigen::Matrix<Extended, Eigen::Dynamic, 1>;
3741 const Eigen::Index n = factor->n;
3742 const Eigen::Index rk = factor->rk;
3743 const Extended sigma2_ext(sigma2);
3744 const Extended unit_work =
3745 gpr::extended::WorkingPrecision<Extended>::unitRoundoff();
3746 const Extended n_ext = static_cast<Extended>(n);
3747 const Extended r_ext = static_cast<Extended>(rk);
3748 const Extended nr_order = n_ext + r_ext + 4.0L;
3749 const Extended sum_order = n_ext + r_ext + 4.0L;
3750 if (!(nr_order * unit_work < 1.0L) || !(sum_order * unit_work < 1.0L)) {
3751 throw BorderedVarianceError(
3752 "the bordered covariance order exceeds unit roundoff resolution");
3753 }
3754 const Extended gamma_r_work =
3755 (rk > 0) ? (r_ext * unit_work) / (1.0L - r_ext * unit_work) : 0.0L;
3756 const Extended gamma_nr_work =
3757 (nr_order * unit_work) / (1.0L - nr_order * unit_work);
3758 const Extended gamma_sum_work =
3759 (sum_order * unit_work) / (1.0L - sum_order * unit_work);
3760
3761 const Extended w_lo =
3762 (sigma2 > 0.0) ? (Extended(1) / sigma2_ext) : Extended(0);
3763
3764 Eigen::MatrixXd rhs_projected;
3765 const Eigen::MatrixXd* rhs_effective = &rhs;
3766 if (bordered_deflation_) {
3767 rhs_projected = bordered_deflation_->projectRows(rhs);
3768 rhs_effective = &rhs_projected;
3769 }
3770
3771 for (Eigen::Index column = 0; column < rhs.cols(); ++column) {
3772 const Extended prior = static_cast<Extended>(prior_diag(column));
3773 const ExtendedVector k_vec =
3774 rhs_effective->col(column).cast<Extended>();
3775 const Extended k_norm = k_vec.norm();
3776
3777 ExtendedVector y_q(rk), w_q(rk), alpha(rk);
3778 ExtendedVector k_perp = k_vec;
3779 Extended q_k_perp = 0.0L;
3780 ExtendedVector v_q = ExtendedVector::Zero(n);
3781 if (rk > 0) {
3782 y_q = factor->Q.transpose() * k_vec;
3783 k_perp.noalias() -= factor->Q * y_q;
3784 const ExtendedVector dy = factor->Q.transpose() * k_perp;
3785 k_perp.noalias() -= factor->Q * dy;
3786 y_q += dy;
3787 q_k_perp = (factor->Q.transpose() * k_perp).norm();
3788
3789 w_q = y_q;
3790 rm_cache->Rm.transpose()
3791 .template triangularView<Eigen::Lower>()
3792 .solveInPlace(w_q);
3793 alpha = w_q;
3794 rm_cache->Rm.template triangularView<Eigen::Upper>().solveInPlace(
3795 alpha);
3796 v_q = -(factor->Q * alpha);
3797 }
3798
3799 const Extended k_perp_norm2 = k_perp.squaredNorm();
3800 const Extended k_perp_norm = workingSqrt(k_perp_norm2);
3801 const ExtendedVector v_perp = -w_lo * k_perp;
3802 const Extended w_perp2 = w_lo * k_perp_norm2;
3803 const ExtendedVector v = v_q + v_perp;
3804
3805 Extended schur = prior;
3806 Extended correction = 0.0L;
3807 auto neumaier_add = [&](const Extended term) {
3808 const Extended next = schur + term;
3809 correction += workingAbs(schur) >= workingAbs(term)
3810 ? (schur - next) + term
3811 : (term - next) + schur;
3812 schur = next;
3813 };
3814 if (rk > 0) {
3815 for (Eigen::Index row = 0; row < rk; ++row)
3816 neumaier_add(-w_q(row) * w_q(row));
3817 }
3818 if (w_perp2 > 0.0L) neumaier_add(-w_perp2);
3819 schur += correction;
3820 if (!workingIsFinite(schur)) {
3821 throw BorderedVarianceError(
3822 "the bordered covariance is not positive semidefinite");
3823 }
3824
3825 const Extended y_q_norm = (rk > 0) ? y_q.norm() : 0.0L;
3826 const Extended w_q_norm = (rk > 0) ? w_q.norm() : 0.0L;
3827 const Extended alpha_norm = (rk > 0) ? alpha.norm() : 0.0L;
3828 const Extended v_norm2 = v.squaredNorm();
3829 const Extended v_norm = workingSqrt(v_norm2);
3830
3831 const Extended rho_split =
3832 2.0L * gamma_nr_work * (k_norm + factor->q_norm_f * y_q_norm);
3833 const Extended delta_y =
3834 (rk > 0) ? gamma_r_work * (rm_cache->Rm.transpose().cwiseAbs() *
3835 w_q.cwiseAbs())
3836 .norm()
3837 : 0.0L;
3838 const Extended delta_w =
3839 (rk > 0) ? gamma_r_work *
3840 (rm_cache->Rm.cwiseAbs() * alpha.cwiseAbs()).norm()
3841 : 0.0L;
3842 const Extended rho_solve = rm_cache->rm_norm_2 * delta_w + delta_y;
3843
3844 const Extended e_split_q = directedUpper(
3845 Extended(2) *
3846 (gamma_nr_work * factor->q_norm_f * k_norm * alpha_norm +
3847 rho_split * (alpha_norm + w_lo * k_perp_norm) +
3848 w_lo * y_q_norm * q_k_perp),
3849 kESplitQOps);
3850 const Extended e_solve_q = directedUpper(
3851 Extended(2) * delta_y * alpha_norm + delta_w * delta_w +
3852 rm_cache->rm_residual * alpha_norm * alpha_norm,
3853 kESolveQOps);
3854 const Extended qt_v_err = directedUpper(
3855 factor->q_orth_res * alpha_norm + w_lo * q_k_perp, kQtVErrOps);
3856 const Extended e_orth_q = directedUpper(
3857 factor->r_norm_f2 * qt_v_err *
3858 (Extended(2) * alpha_norm + qt_v_err) +
3859 sigma2_ext * (factor->q_orth_res * alpha_norm * alpha_norm +
3860 Extended(2) * w_lo * alpha_norm * q_k_perp),
3861 kEOrthQOps);
3862 const Extended e_sum = directedUpper(
3863 gamma_sum_work * (prior + w_q_norm * w_q_norm + w_perp2), kESumOps);
3864 const Extended e_kernel =
3865 directedUpper(factor->eps_k * v_norm2, kEKernelOps);
3866 const Extended e_q_hi = directedUpper(
3867 e_split_q + e_solve_q + e_orth_q + e_sum + e_kernel, kEQHiSumOps);
3868
3869 // sigma^2 > 0 absorbs the complement into Rm. At sigma^2 = 0 the
3870 // complement is the exact null component and stays in the residual.
3871 const Extended r_perp = (sigma2 > 0.0) ? Extended(0) : k_perp_norm;
3872 const Extended r_norm = directedUpper(
3873 rho_split +
3874 factor->q_norm_2 *
3875 (rho_solve + rm_cache->rm_residual * alpha_norm +
3876 factor->r_norm_f2 *
3877 (factor->q_orth_res * alpha_norm + w_lo * q_k_perp)) +
3878 r_perp + factor->eps_k * v_norm,
3879 kRNormOps);
3880 const Extended r2 = directedUpper(r_norm * r_norm, kSquareOps);
3881 const Extended e_res = directedUpper(r2 / rm_cache->mu_min, kResDivOps);
3882 const Extended e_lower = directedUpper(e_q_hi + e_res, kELowerAddOps);
3883 const Extended e_upper = e_q_hi;
3884 if (!workingIsFinite(e_lower) || !workingIsFinite(e_upper)) {
3885 throw BorderedVarianceError(
3886 "the bordered variance error bound is not finite");
3887 }
3888
3889 Extended raw_lo = schur - e_lower;
3890 Extended raw_hi = schur + e_upper;
3891 if (!workingIsFinite(raw_lo) || !workingIsFinite(raw_hi)) {
3892 throw BorderedVarianceError(
3893 "the bordered variance interval is not finite");
3894 }
3896 if (!(raw_hi >= Extended(0))) {
3897 throw BorderedVarianceError(
3898 "the bordered variance upper bound is negative");
3899 }
3900 if (raw_lo < Extended(0)) raw_lo = Extended(0);
3901 }
3902 const double lo = gpr::extended::roundDownToDouble(raw_lo);
3903 const double hi = gpr::extended::roundUpToDouble(raw_hi);
3904 if (!(hi >= lo)) {
3905 throw BorderedVarianceError(
3906 "bordered variance interval endpoints are inconsistent");
3907 }
3908 intervals[static_cast<std::size_t>(column)] = {lo, hi};
3909 }
3910 return intervals;
3911}
double roundDownToDouble(Work value)

◆ noisyEigenvalues()

const Eigen::VectorXd & gpr::StableBasisND::noisyEigenvalues ( ) const
inline

Definition at line 960 of file StableBasis.h.

961 {
962 return noisy_eigvals_;
963 }

◆ noisyInverse()

Eigen::MatrixXd gpr::StableBasisND::noisyInverse ( double sigma2) const

Definition at line 4137 of file StableBasis.cpp.

4138{
4139 sigma2 = conditionFlooredSigma2(Sr_, sigma2, Psi_.rows());
4140 // (K+sigma2 I)^-1 = Psi diag(1/(S^2+sigma2)) Psi^T + (1/sigma2)(I-Psi
4141 // Psi^T)
4142 const Eigen::Index n = Psi_.rows();
4143 if (n == 0 || Psi_.cols() != Sr_.size() || !(sigma2 > 0.0)) {
4144 return Eigen::MatrixXd();
4145 }
4146 const Eigen::ArrayXd mu =
4147 hasNoisyEigenvalues() ? Eigen::ArrayXd(noisy_eigvals_.array())
4148 : Eigen::ArrayXd(Sr_.array().square() + sigma2);
4149 const double q = Psi_.cols() == n ? 0.0 : 1.0 / sigma2;
4150 const Eigen::ArrayXd d = mu.inverse() - q;
4151 Eigen::MatrixXd inv = Eigen::MatrixXd::Identity(n, n) * q;
4152 inv.noalias() += Psi_ * d.matrix().asDiagonal() * Psi_.transpose();
4153 return inv;
4154}

◆ noisyInverseDiagonal()

Eigen::VectorXd gpr::StableBasisND::noisyInverseDiagonal ( double sigma2) const

Definition at line 3913 of file StableBasis.cpp.

3914{
3915 // Same regularized operator as the mean path: every mean, logdet,
3916 // and LOO route floors sigma2 through conditionFlooredSigma2; a raw
3917 // sigma2 here yields moments of a DIFFERENT posterior (systematic
3918 // overconfidence exactly when the floor is active).
3919 sigma2 = conditionFlooredSigma2(Sr_, sigma2, Psi_.rows());
3920 if (Psi_.rows() == 0 || Psi_.cols() != Sr_.size() || !(sigma2 > 0.0)) {
3921 return Eigen::VectorXd();
3922 }
3923
3924 const Eigen::ArrayXd shrink =
3925 Sr_.array().square() / (Sr_.array().square() + sigma2);
3926 // diag_i = sum_j psi_ij^2/(s_j^2 + sigma2) + w_c (1 - sum_j psi_ij^2),
3927 // w_c the complement weight (1/sigma2 when nothing above the resolution
3928 // cutoff was dropped). Leave-one-out scores and the variance
3929 // calibration pair this diagonal with alpha from solveNoisy, so both
3930 // carry the mean-path weight of one (K + sigma2 I)^-1; joint posterior
3931 // covariance uses covarianceComplementWeight.
3932 const double w_c = complementWeight(sigma2);
3933 Eigen::VectorXd diag = Eigen::VectorXd::Constant(Psi_.rows(), w_c);
3934 for (Eigen::Index j = 0; j < Psi_.cols(); ++j) {
3935 const double inv_noisy = 1.0 / (Sr_(j) * Sr_(j) + sigma2);
3936 diag.array() += (inv_noisy - w_c) * Psi_.col(j).array().square();
3937 }
3938 return diag;
3939}

◆ noisyInverseDiagonalEntries()

Eigen::VectorXd gpr::StableBasisND::noisyInverseDiagonalEntries ( const Eigen::VectorXi & rows,
double sigma2 ) const

Definition at line 3941 of file StableBasis.cpp.

3943{
3944 // Floored identically to noisyInverseDiagonal; the two must describe
3945 // the same posterior or a caller mixing them sees two noise models.
3946 sigma2 = conditionFlooredSigma2(Sr_, sigma2, Psi_.rows());
3947 if (Psi_.rows() == 0 || Psi_.cols() != Sr_.size() || !(sigma2 > 0.0)) {
3948 return Eigen::VectorXd();
3949 }
3950
3951 const Eigen::ArrayXd shrink =
3952 Sr_.array().square() / (Sr_.array().square() + sigma2);
3953 const double inv_sigma2 = 1.0 / sigma2;
3954 Eigen::VectorXd out(rows.size());
3955 for (Eigen::Index r = 0; r < rows.size(); ++r) {
3956 const Eigen::Index row = rows(r);
3957 if (row < 0 || row >= Psi_.rows()) {
3958 out(r) = std::numeric_limits<double>::quiet_NaN();
3959 continue;
3960 }
3961 double value = complementWeight(sigma2);
3962 for (Eigen::Index j = 0; j < Psi_.cols(); ++j) {
3963 const double inv_noisy = 1.0 / (Sr_(j) * Sr_(j) + sigma2);
3964 value += (inv_noisy - complementWeight(sigma2)) * Psi_(row, j) *
3965 Psi_(row, j);
3966 }
3967 (void)inv_sigma2;
3968 (void)shrink;
3969 out(r) = value;
3970 }
3971 return out;
3972}
eon_relax_band_t eon_relax_surface_fn void eon_relax_outcome_t * out

◆ noisyInverseSandwichDiagonal()

Eigen::VectorXd gpr::StableBasisND::noisyInverseSandwichDiagonal ( const Eigen::MatrixXd & dK,
double sigma2 ) const

Definition at line 4059 of file StableBasis.cpp.

4061{
4062 // Same regularized operator as the mean path: every mean, logdet,
4063 // and LOO route floors sigma2 through conditionFlooredSigma2; a raw
4064 // sigma2 here yields moments of a DIFFERENT posterior (systematic
4065 // overconfidence exactly when the floor is active).
4066 sigma2 = conditionFlooredSigma2(Sr_, sigma2, Psi_.rows());
4067 if (Psi_.rows() == 0 || Psi_.cols() != Sr_.size() || !(sigma2 > 0.0) ||
4068 dK.rows() != Psi_.rows() || dK.cols() != Psi_.rows()) {
4069 return Eigen::VectorXd();
4070 }
4071
4072 if (Psi_.cols() == Psi_.rows()) {
4073 // With no orthogonal complement, contract the inverse spectrum
4074 // directly instead of subtracting four noise-scaled projector terms.
4075 const Eigen::ArrayXd mu =
4077 ? Eigen::ArrayXd(noisy_eigvals_.array())
4078 : Eigen::ArrayXd(Sr_.array().square() + sigma2);
4079 const Eigen::MatrixXd scaled =
4080 Psi_ * mu.inverse().matrix().asDiagonal();
4081 const Eigen::MatrixXd projected = Psi_.transpose() * dK * Psi_;
4082 const Eigen::MatrixXd action = scaled * projected;
4083 return (action.array() * scaled.array()).rowwise().sum();
4084 }
4085
4086 const double inv_noise = 1.0 / sigma2;
4087 const Eigen::VectorXd shrink =
4088 (Sr_.array().square() / (Sr_.array().square() + sigma2)).matrix();
4089 const Eigen::MatrixXd Urho = Psi_ * shrink.asDiagonal();
4090
4091 const Eigen::MatrixXd dKT_U = dK.transpose() * Psi_;
4092 const Eigen::VectorXd left = (Urho.array() * dKT_U.array()).rowwise().sum();
4093 const Eigen::MatrixXd dK_Urho = dK * Urho;
4094 const Eigen::VectorXd right =
4095 (dK_Urho.array() * Psi_.array()).rowwise().sum();
4096
4097 const Eigen::MatrixXd projected = Psi_.transpose() * dK * Psi_;
4098 const Eigen::MatrixXd Urho_projected = Urho * projected;
4099 const Eigen::VectorXd low_rank =
4100 (Urho_projected.array() * Urho.array()).rowwise().sum();
4101
4102 return inv_noise * inv_noise * (dK.diagonal() - left - right + low_rank);
4103}

◆ noisyPosteriorWeights()

StableBasisPosteriorWeights gpr::StableBasisND::noisyPosteriorWeights ( const Eigen::VectorXd & y,
double sigma2 ) const

Definition at line 3048 of file StableBasis.cpp.

3050{
3051 sigma2 = conditionFlooredSigma2(Sr_, sigma2, Psi_.rows());
3052 const Eigen::VectorXd z = Psi_.transpose() * y;
3053 // mu_i = S_i^2 + sigma2, the eigenvalues of K + sigma2 I. When the basis
3054 // was built from the noisy kernel directly (factorizeNoisyKernel), use the
3055 // stored mu_i so the inverse never re-forms the cancelling sum S_i^2 +
3056 // sigma2 (the signal S_i^2 = mu_i - sigma2 lost digits at assembly).
3057 const Eigen::ArrayXd mu =
3058 hasNoisyEigenvalues() ? Eigen::ArrayXd(noisy_eigvals_.array())
3059 : Eigen::ArrayXd(Sr_.array().square() + sigma2);
3060 const Eigen::ArrayXd s2 = mu - sigma2;
3061 const Eigen::ArrayXd shrink =
3062 stablePosteriorShrinkage(s2, sigma2, Psi_.rows());
3063 Eigen::ArrayXd projected_inverse = mu.inverse();
3064 for (Eigen::Index i = 0; i < projected_inverse.size(); ++i) {
3065 if (s2(i) > 0.0) projected_inverse(i) = shrink(i) / s2(i);
3066 }
3067 const Eigen::VectorXd noisy_projected =
3068 Psi_ * (projected_inverse * z.array()).matrix();
3069 StableBasisPosteriorWeights weights;
3070 weights.alpha = noisy_projected;
3071 const double complement = complementWeight(sigma2);
3072 if (complement > 0.0) {
3073 weights.alpha += complement * (y - Psi_ * z);
3074 }
3075 weights.reduced = (shrink * z.array()).matrix();
3076 return weights;
3077}

◆ noisyRangeSelfQuadratic()

Eigen::VectorXd gpr::StableBasisND::noisyRangeSelfQuadratic ( const Eigen::MatrixXd & rhs,
double sigma2 ) const

Definition at line 3125 of file StableBasis.cpp.

3127{
3128 // Same regularized operator as the mean path: every mean, logdet,
3129 // and LOO route floors sigma2 through conditionFlooredSigma2; a raw
3130 // sigma2 here yields moments of a DIFFERENT posterior (systematic
3131 // overconfidence exactly when the floor is active).
3132 sigma2 = conditionFlooredSigma2(Sr_, sigma2, Psi_.rows());
3133 if (rhs.rows() != Psi_.rows() || Psi_.cols() != Sr_.size() ||
3134 !(sigma2 > 0.0)) {
3135 return Eigen::VectorXd();
3136 }
3137 if (rhs.cols() == 0) return Eigen::VectorXd();
3138
3139 const Eigen::MatrixXd z = Psi_.transpose() * rhs;
3140 const Eigen::ArrayXd inv_projected =
3141 (Sr_.array().square() + sigma2).inverse();
3142 Eigen::VectorXd quad(rhs.cols());
3143 for (Eigen::Index j = 0; j < rhs.cols(); ++j) {
3144 quad(j) = (z.col(j).array().square() * inv_projected).sum();
3145 }
3146 return quad;
3147}

◆ noisySelfQuadratic()

Eigen::VectorXd gpr::StableBasisND::noisySelfQuadratic ( const Eigen::MatrixXd & rhs,
double sigma2 ) const

Definition at line 3100 of file StableBasis.cpp.

3102{
3103 if (rhs.rows() != Psi_.rows() || Psi_.cols() != Sr_.size() ||
3104 !(sigma2 > 0.0)) {
3105 return Eigen::VectorXd();
3106 }
3107 if (rhs.cols() == 0) return Eigen::VectorXd();
3108
3109 const Eigen::MatrixXd z = Psi_.transpose() * rhs;
3110 const Eigen::ArrayXd inv_projected =
3111 (Sr_.array().square() + sigma2).inverse();
3112 Eigen::VectorXd quad(rhs.cols());
3113 for (Eigen::Index j = 0; j < rhs.cols(); ++j) {
3114 const double projected =
3115 (z.col(j).array().square() * inv_projected).sum();
3116 const double residual2 = (rhs.col(j) - Psi_ * z.col(j)).squaredNorm();
3117 // y^T (K + sigma2 I)^-1 y with the inverse solveNoisy applies to the
3118 // targets, so the complement keeps the mean-path weight; posterior
3119 // covariance subtractions use covarianceComplementWeight instead.
3120 quad(j) = projected + residual2 * complementWeight(sigma2);
3121 }
3122 return quad;
3123}

◆ numBasis()

int gpr::StableBasisND::numBasis ( ) const
inline

Definition at line 940 of file StableBasis.h.

941 {
942 return static_cast<int>(midx_.rows());
943 }

◆ numObs()

Eigen::Index gpr::StableBasisND::numObs ( ) const
inline

Definition at line 946 of file StableBasis.h.

947 {
948 return Psi_.rows();
949 }

◆ permuteObservationRows()

bool gpr::StableBasisND::permuteObservationRows ( const Eigen::VectorXi & source_for_target)

Definition at line 1782 of file StableBasis.cpp.

1784{
1785 const Eigen::Index n = Psi_.rows();
1786 if (source_for_target.size() != n) return false;
1787 std::vector<unsigned char> seen(static_cast<std::size_t>(n), 0);
1788 Eigen::MatrixXd Psi_next(Psi_.rows(), Psi_.cols());
1789 Eigen::MatrixXd A_next;
1790 const bool permute_design = A_train_.rows() == n;
1791 if (A_train_.size() > 0 && !permute_design) return false;
1792 if (permute_design) A_next.resize(A_train_.rows(), A_train_.cols());
1793
1794 for (Eigen::Index target = 0; target < n; ++target) {
1795 const Eigen::Index src = source_for_target(target);
1796 if (src < 0 || src >= n) return false;
1797 auto& visited = seen[static_cast<std::size_t>(src)];
1798 if (visited != 0) return false;
1799 visited = 1;
1800 Psi_next.row(target) = Psi_.row(src);
1801 if (permute_design) A_next.row(target) = A_train_.row(src);
1802 }
1803
1804 Psi_ = std::move(Psi_next);
1805 if (permute_design) A_train_ = std::move(A_next);
1806 if (bordered_kernel_.rows() == n && bordered_kernel_.cols() == n) {
1807 Eigen::MatrixXd K_next(n, n);
1808 for (Eigen::Index r = 0; r < n; ++r) {
1809 const Eigen::Index sr = source_for_target(r);
1810 for (Eigen::Index c = 0; c < n; ++c) {
1811 K_next(r, c) = bordered_kernel_(sr, source_for_target(c));
1812 }
1813 }
1814 bordered_kernel_ = std::move(K_next);
1815 } else {
1816 bordered_kernel_.resize(0, 0);
1817 bordered_assembly_error_ = 0.0;
1818 }
1819 clearBorderedCache();
1820 return true;
1821}

◆ posteriorCovariance()

Eigen::MatrixXd gpr::StableBasisND::posteriorCovariance ( const Eigen::MatrixXd & cross,
const Eigen::MatrixXd & prior,
double sigma2 ) const

Joint posterior covariance from the same exact eigenmode sums.

Off-diagonal entries share the diagonal's unresolved-tail and noise-damped mode decomposition, so linear actions and covariance blocks describe one posterior. The diagonal is posteriorVarianceDiagonal and is not projected; stabilizePosteriorCovariance makes the matrix positive semidefinite once the caller has validated it. Throws linalg::StableVarianceError like posteriorVarianceDiagonal.

Definition at line 4489 of file StableBasis.cpp.

4492{
4493 if (prior.rows() != prior.cols() || prior.rows() != cross.cols())
4494 throw linalg::StableVarianceError(
4495 "stable posterior covariance: prior and query columns disagree");
4496 const Eigen::VectorXd diagonal =
4497 posteriorVarianceDiagonal(cross, prior.diagonal(), sigma2);
4498 sigma2 = varianceFlooredSigma2(Sr_, sigma2, Psi_.rows());
4499
4500 Eigen::MatrixXd projected, residual;
4501 projectOntoStableBasis(Psi_, cross, projected, residual);
4502 Eigen::MatrixXd retained = projected;
4503 for (Eigen::Index mode = 0; mode < Sr_.size(); ++mode) {
4504 if (!(Sr_(mode) > 0.0) || !std::isfinite(Sr_(mode)))
4505 throw linalg::StableVarianceError(
4506 "stable posterior covariance: retained singular value is not "
4507 "finite and positive");
4508 retained.row(mode) /= Sr_(mode);
4509 }
4510 const bool use_complement = dropped_s2_max_ > 0.0;
4511 Eigen::MatrixXd complement;
4512 if (use_complement) {
4513 if (!std::isfinite(dropped_s2_max_))
4514 throw linalg::StableVarianceError(
4515 "stable posterior covariance: complement eigenvalue is not "
4516 "finite");
4517 complement = residual / std::sqrt(dropped_s2_max_);
4518 }
4519
4520 // For each pair, combine the unresolved-tail subtraction and the
4521 // noise-damped retained terms in one exact accumulator:
4522 // T_ij = K_ij - sum_m c_mi c_mj,
4523 // C_ij = T_ij + sum_m sigma2/(s_m^2+sigma2) c_mi c_mj.
4524 // The diagonal is the explicitly nonnegative form; sharing these exact
4525 // pair reductions keeps the surrounding covariance and every linear
4526 // action consistent with it.
4527 Eigen::MatrixXd covariance(prior.rows(), prior.cols());
4528 for (Eigen::Index column = 0; column < prior.cols(); ++column) {
4529 for (Eigen::Index row = 0; row < column; ++row) {
4530 linalg::ExactSum value;
4531 value.add(prior(row, column));
4532 for (Eigen::Index mode = 0; mode < Sr_.size(); ++mode) {
4533 value.addProduct(-retained(mode, row), retained(mode, column));
4534 const double s2 = Sr_(mode) * Sr_(mode);
4535 value.addTripleProduct(retained(mode, row),
4536 retained(mode, column),
4537 sigma2 / (s2 + sigma2));
4538 }
4539 if (use_complement) {
4540 const double attenuation = sigma2 / (dropped_s2_max_ + sigma2);
4541 for (Eigen::Index mode = 0; mode < complement.rows(); ++mode) {
4542 value.addProduct(-complement(mode, row),
4543 complement(mode, column));
4544 value.addTripleProduct(complement(mode, row),
4545 complement(mode, column),
4546 attenuation);
4547 }
4548 }
4549 covariance(row, column) = value.value();
4550 covariance(column, row) = covariance(row, column);
4551 }
4552 covariance(column, column) = diagonal(column);
4553 }
4554 return covariance;
4555}
Eigen::VectorXd posteriorVarianceDiagonal(const Eigen::MatrixXd &cross, const Eigen::VectorXd &prior, double sigma2) const
Cancellation-free posterior diagonal for arbitrary query channels.

◆ posteriorMeanEnergy()

Eigen::VectorXd gpr::StableBasisND::posteriorMeanEnergy ( const Eigen::MatrixXd & Xstar,
const Eigen::VectorXd & alpha ) const

Definition at line 4341 of file StableBasis.cpp.

4343{
4344 // mu(x*) = k*(x*)^T alpha, k*(x*) = A(x*) A_train^T, so
4345 // mu(x*) = A_E(x*) (A_train^T alpha).
4346 Eigen::MatrixXd A_E;
4347 std::vector<Eigen::MatrixXd> A_g;
4348 designAt(Xstar, A_E, A_g);
4349 const Eigen::VectorXd v =
4350 A_train_.transpose() * posteriorMeanWeights(alpha); // N
4351 return A_E * v;
4352}
Eigen::VectorXd posteriorMeanWeights(const Eigen::VectorXd &alpha) const

◆ posteriorMeanGradient()

Eigen::MatrixXd gpr::StableBasisND::posteriorMeanGradient ( const Eigen::MatrixXd & Xstar,
const Eigen::VectorXd & alpha ) const

Definition at line 4354 of file StableBasis.cpp.

4356{
4357 Eigen::MatrixXd A_E;
4358 std::vector<Eigen::MatrixXd> A_g;
4359 designAt(Xstar, A_E, A_g);
4360 const Eigen::VectorXd v =
4361 A_train_.transpose() * posteriorMeanWeights(alpha); // N
4362 Eigen::MatrixXd G(Xstar.rows(), dim_);
4363 for (int j = 0; j < dim_; ++j)
4364 G.col(j) = A_g[j] * v;
4365 return G;
4366}

◆ posteriorMeanReducedCoeffs()

Eigen::VectorXd gpr::StableBasisND::posteriorMeanReducedCoeffs ( const Eigen::VectorXd & y,
double sigma2 ) const

Definition at line 2847 of file StableBasis.cpp.

2849{
2850 // p_i = S_i^2/(S_i^2+sigma2) * (Psi^T y)_i. predictEnergy(x*, p) then
2851 // yields A_E(x*) W p = A_E(x*) A_train^T (K+sigma2 I)^{-1} y without
2852 // forming alpha.
2853 const Eigen::ArrayXd s2 = Sr_.array().square();
2854 const Eigen::ArrayXd shrink =
2855 stablePosteriorShrinkage(s2, sigma2, Psi_.rows());
2856 return (shrink * (Psi_.transpose() * y).array()).matrix();
2857}

◆ posteriorMeanWeights()

Eigen::VectorXd gpr::StableBasisND::posteriorMeanWeights ( const Eigen::VectorXd & alpha) const

Definition at line 4330 of file StableBasis.cpp.

4332{
4333 if (!linalg::stablePosteriorVarianceEnabled() || dropped_s2_max_ > 0.0 ||
4334 Psi_.cols() == Psi_.rows() || alpha.size() != Psi_.rows())
4335 return alpha;
4336 Eigen::VectorXd coefficients = Psi_.transpose() * alpha;
4337 coefficients += Psi_.transpose() * (alpha - Psi_ * coefficients);
4338 return Psi_ * coefficients;
4339}
bool stablePosteriorVarianceEnabled() noexcept
Whether stable posterior variance reductions are enabled.
Definition ExactSchur.h:40

◆ posteriorVarianceAction()

double gpr::StableBasisND::posteriorVarianceAction ( const Eigen::MatrixXd & cross,
const Eigen::MatrixXd & prior,
const Eigen::VectorXd & weights,
double sigma2 ) const

Variance of a linear action on a joint query covariance, evaluated by the same nonnegative eigenmode decomposition.

Returns NaN when the rounded basis cannot represent the action as nonnegative and throws linalg::StableVarianceError on a shape mismatch or a non-positive noise floor.

Definition at line 4557 of file StableBasis.cpp.

4561{
4562 if (prior.rows() != prior.cols() || prior.rows() != cross.cols() ||
4563 weights.size() != prior.rows() || cross.rows() != Psi_.rows() ||
4564 Psi_.cols() != Sr_.size())
4565 throw linalg::StableVarianceError(
4566 "stable posterior action variance: weights, prior and cross "
4567 "covariance disagree");
4568 sigma2 = varianceFlooredSigma2(Sr_, sigma2, Psi_.rows());
4569 if (!(sigma2 > 0.0) || !std::isfinite(sigma2))
4570 throw linalg::StableVarianceError(
4571 "stable posterior action variance: noise floor is not finite and "
4572 "positive");
4573
4574 Eigen::MatrixXd action(cross.rows(), 1);
4575 for (Eigen::Index row = 0; row < cross.rows(); ++row) {
4576 linalg::ExactSum value;
4577 for (Eigen::Index column = 0; column < cross.cols(); ++column)
4578 value.addProduct(cross(row, column), weights(column));
4579 action(row, 0) = value.value();
4580 }
4581 Eigen::MatrixXd projected, residual;
4582 projectOntoStableBasis(Psi_, action, projected, residual);
4583
4584 linalg::ExactSum local_prior;
4585 for (Eigen::Index column = 0; column < prior.cols(); ++column)
4586 for (Eigen::Index row = 0; row < prior.rows(); ++row)
4587 local_prior.addTripleProduct(weights(row), prior(row, column),
4588 weights(column));
4589 return nonnegativeEigenmodeVariance(
4590 projected.col(0), residual.col(0), Sr_, sigma2,
4591 covarianceComplementEigenvalue(), dropped_s2_max_ > 0.0, local_prior);
4592}
double covarianceComplementEigenvalue() const noexcept
Largest signal eigenvalue represented by the discarded covariance complement.

◆ posteriorVarianceDiagonal()

Eigen::VectorXd gpr::StableBasisND::posteriorVarianceDiagonal ( const Eigen::MatrixXd & cross,
const Eigen::VectorXd & prior,
double sigma2 ) const

Cancellation-free posterior diagonal for arbitrary query channels.

Each entry is one ExactSum of the nonnegative unresolved tail and the noise-damped retained and resolved-complement eigenmode terms, at the noise varianceFlooredNoise(sigma2). A null complement leaves the query's residual in the unresolved tail. An entry the rounded basis cannot represent as nonnegative is NaN; callers reject it with linalg::requireStablePosteriorVariance after any training-row identity is applied. A shape mismatch or a non-positive noise floor throws linalg::StableVarianceError.

Definition at line 4455 of file StableBasis.cpp.

4458{
4459 sigma2 = varianceFlooredSigma2(Sr_, sigma2, Psi_.rows());
4460 if (cross.rows() != Psi_.rows() || prior.size() != cross.cols() ||
4461 Psi_.cols() != Sr_.size())
4462 throw linalg::StableVarianceError(
4463 "stable posterior variance: cross covariance does not match the "
4464 "stable basis");
4465 if (!(sigma2 > 0.0) || !std::isfinite(sigma2))
4466 throw linalg::StableVarianceError(
4467 "stable posterior variance: noise floor is not finite and "
4468 "positive");
4469
4470 Eigen::MatrixXd projected, residual;
4471 projectOntoStableBasis(Psi_, cross, projected, residual);
4472 // A complement whose spectrum is below the eigensolver's backward-error
4473 // threshold is the null space of the retained model. Its cross residual
4474 // is projection roundoff and belongs in the unresolved prior tail; do not
4475 // divide it by an invented signal eigenvalue.
4476 const bool use_complement = dropped_s2_max_ > 0.0;
4477 const double complement_eigenvalue = covarianceComplementEigenvalue();
4478 Eigen::VectorXd variance(prior.size());
4479 for (Eigen::Index column = 0; column < cross.cols(); ++column) {
4480 linalg::ExactSum local_prior;
4481 local_prior.add(prior(column));
4482 variance(column) = nonnegativeEigenmodeVariance(
4483 projected.col(column), residual.col(column), Sr_, sigma2,
4484 complement_eigenvalue, use_complement, local_prior);
4485 }
4486 return variance;
4487}
double variance(const Weights &w, const Matrix &covariance)

◆ posteriorVarianceEnergy()

Eigen::VectorXd gpr::StableBasisND::posteriorVarianceEnergy ( const Eigen::MatrixXd & Xstar,
double sigma2 ) const

Definition at line 4690 of file StableBasis.cpp.

4692{
4693 Eigen::MatrixXd A_E;
4694 std::vector<Eigen::MatrixXd> A_g;
4695 designAt(Xstar, A_E, A_g);
4696 return rangeVarianceFromDesign(A_E, sigma2);
4697}

◆ posteriorVarianceEnergyAffine()

Eigen::VectorXd gpr::StableBasisND::posteriorVarianceEnergyAffine ( const Eigen::MatrixXd & Ustar,
const Eigen::MatrixXd & residuals,
double sigma2 ) const

Definition at line 4699 of file StableBasis.cpp.

4702{
4703 Eigen::MatrixXd A_E;
4704 AffineVariancePrior affine_prior;
4705 designAtAffineEnergy(Ustar, residuals, A_E, &affine_prior);
4706 if (affine_prior.stable) {
4707 // Form the missing mass independently of the binary64 design entries.
4708 // Their rounded squared norm can exceed the prior for near-span
4709 // queries.
4710 for (Eigen::Index i = 0; i < affine_prior.diagonal.size(); ++i)
4711 affine_prior.diagonal(i) *= DesignVarianceReal(
4712 affineResidualTail(residuals.row(i).squaredNorm()));
4713 }
4714 return rangeVarianceFromDesign(A_E, sigma2, &affine_prior);
4715}

◆ predictEnergy()

Eigen::VectorXd gpr::StableBasisND::predictEnergy ( const Eigen::MatrixXd & Xstar,
const Eigen::VectorXd & b ) const

Definition at line 2624 of file StableBasis.cpp.

2626{
2627 Eigen::MatrixXd A_E;
2628 std::vector<Eigen::MatrixXd> A_g;
2629 designAt(Xstar, A_E, A_g);
2630 return (A_E * W_) * b;
2631}

◆ predictEnergyAffine()

Eigen::VectorXd gpr::StableBasisND::predictEnergyAffine ( const Eigen::MatrixXd & Ustar,
const Eigen::MatrixXd & residuals,
const Eigen::VectorXd & b ) const

Definition at line 2645 of file StableBasis.cpp.

2648{
2649 Eigen::MatrixXd A_E;
2650 designAtAffineEnergy(Ustar, residuals, A_E);
2651 return (A_E * W_) * b;
2652}

◆ predictGradient()

Eigen::MatrixXd gpr::StableBasisND::predictGradient ( const Eigen::MatrixXd & Xstar,
const Eigen::VectorXd & b ) const

Definition at line 2633 of file StableBasis.cpp.

2635{
2636 Eigen::MatrixXd A_E;
2637 std::vector<Eigen::MatrixXd> A_g;
2638 designAt(Xstar, A_E, A_g);
2639 Eigen::MatrixXd G(Xstar.rows(), dim_);
2640 for (int j = 0; j < dim_; ++j)
2641 G.col(j) = (A_g[j] * W_) * b;
2642 return G;
2643}

◆ predictGradientAffine()

Eigen::MatrixXd gpr::StableBasisND::predictGradientAffine ( const Eigen::MatrixXd & Ustar,
const Eigen::MatrixXd & residuals,
const Eigen::MatrixXd & basis,
const Eigen::VectorXd & b ) const

Definition at line 2663 of file StableBasis.cpp.

2666{
2667 Eigen::MatrixXd Phi;
2668 std::vector<Eigen::MatrixXd> dPhi;
2669 eigenTensor(Ustar, true, Phi, dPhi);
2670 const Eigen::Index m = Ustar.rows();
2671 const Eigen::Index N = midx_.rows();
2672 Eigen::MatrixXd Phi_s =
2673 Phi.array().rowwise() * sqrt_lam_.transpose().array();
2674 std::vector<Eigen::MatrixXd> dPhi_s(dim_);
2675 for (int k = 0; k < dim_; ++k)
2676 dPhi_s[k] = dPhi[k].array().rowwise() * sqrt_lam_.transpose().array();
2677
2678 const Eigen::VectorXd coeff = W_ * b;
2679 const Eigen::VectorXd base_coeff = coeff.head(N);
2680 const double sqrt2 = std::sqrt(2.0);
2681 const Eigen::MatrixXd projector =
2682 Eigen::MatrixXd::Identity(affine_full_dim_, affine_full_dim_) -
2683 basis * basis.transpose();
2684 Eigen::MatrixXd G(m, affine_full_dim_);
2685
2686 for (Eigen::Index i = 0; i < m; ++i) {
2687 const Eigen::RowVectorXd ri = residuals.row(i);
2688 const double scale = std::exp(-ri.squaredNorm());
2689 const double base_value = Phi_s.row(i).dot(base_coeff);
2690 Eigen::VectorXd normal_values(affine_full_dim_);
2691 for (Eigen::Index p = 0; p < affine_full_dim_; ++p) {
2692 normal_values(p) = Phi_s.row(i).dot(coeff.segment((p + 1) * N, N));
2693 }
2694 const double normal_dot = ri.dot(normal_values);
2695
2696 Eigen::RowVectorXd gu = Eigen::RowVectorXd::Zero(dim_);
2697 for (int k = 0; k < dim_; ++k) {
2698 double val = dPhi_s[k].row(i).dot(base_coeff);
2699 for (Eigen::Index p = 0; p < affine_full_dim_; ++p)
2700 val += sqrt2 * ri(p) *
2701 dPhi_s[k].row(i).dot(coeff.segment((p + 1) * N, N));
2702 gu(k) = scale * val;
2703 }
2704
2705 Eigen::RowVectorXd gr(affine_full_dim_);
2706 for (Eigen::Index p = 0; p < affine_full_dim_; ++p) {
2707 gr(p) =
2708 scale * (-2.0 * ri(p) * base_value +
2709 sqrt2 * (normal_values(p) - 2.0 * ri(p) * normal_dot));
2710 }
2711 G.row(i) = gu * basis.transpose() + gr * projector;
2712 }
2713 return G;
2714}

◆ predictGradientHessianVectorAffine()

Eigen::MatrixXd gpr::StableBasisND::predictGradientHessianVectorAffine ( const Eigen::MatrixXd & Ustar,
const Eigen::MatrixXd & residuals,
const Eigen::MatrixXd & basis,
const Eigen::MatrixXd & tangent_directions,
const Eigen::MatrixXd & residual_directions,
const Eigen::VectorXd & b ) const

Definition at line 2716 of file StableBasis.cpp.

2720{
2721 const Eigen::Index m = Ustar.rows();
2722 const Eigen::Index N = midx_.rows();
2723
2724 std::vector<std::vector<Eigen::VectorXd>> V(m), D(m), DD(m);
2725 for (Eigen::Index i = 0; i < m; ++i) {
2726 V[i].resize(dim_);
2727 D[i].resize(dim_);
2728 DD[i].resize(dim_);
2729 for (int k = 0; k < dim_; ++k)
2730 eigen1dSecond(Ustar(i, k), k, V[i][k], D[i][k], DD[i][k]);
2731 }
2732
2733 Eigen::MatrixXd Phi(m, N);
2734 std::vector<Eigen::MatrixXd> dPhi(dim_, Eigen::MatrixXd::Zero(m, N));
2735 std::vector<Eigen::MatrixXd> d2PhiDirection(dim_,
2736 Eigen::MatrixXd::Zero(m, N));
2737
2738 for (Eigen::Index c = 0; c < N; ++c) {
2739 for (Eigen::Index i = 0; i < m; ++i) {
2740 double p = 1.0;
2741 for (int k = 0; k < dim_; ++k)
2742 p *= V[i][k](midx_(c, k));
2743 Phi(i, c) = p;
2744
2745 for (int j = 0; j < dim_; ++j) {
2746 double gp = 1.0;
2747 for (int k = 0; k < dim_; ++k)
2748 gp *=
2749 (k == j) ? D[i][k](midx_(c, k)) : V[i][k](midx_(c, k));
2750 dPhi[j](i, c) = gp;
2751
2752 double hp = 0.0;
2753 for (int l = 0; l < dim_; ++l) {
2754 double term = tangent_directions(i, l);
2755 for (int k = 0; k < dim_; ++k) {
2756 if (k == j && k == l)
2757 term *= DD[i][k](midx_(c, k));
2758 else if (k == j || k == l)
2759 term *= D[i][k](midx_(c, k));
2760 else
2761 term *= V[i][k](midx_(c, k));
2762 }
2763 hp += term;
2764 }
2765 d2PhiDirection[j](i, c) = hp;
2766 }
2767 }
2768 }
2769
2770 const Eigen::MatrixXd Phi_s =
2771 Phi.array().rowwise() * sqrt_lam_.transpose().array();
2772 std::vector<Eigen::MatrixXd> dPhi_s(dim_), d2PhiDirection_s(dim_);
2773 for (int k = 0; k < dim_; ++k) {
2774 dPhi_s[k] = dPhi[k].array().rowwise() * sqrt_lam_.transpose().array();
2775 d2PhiDirection_s[k] =
2776 d2PhiDirection[k].array().rowwise() * sqrt_lam_.transpose().array();
2777 }
2778
2779 const Eigen::VectorXd coeff = W_ * b;
2780 const Eigen::VectorXd base_coeff = coeff.head(N);
2781 const double sqrt2 = std::sqrt(2.0);
2782 const Eigen::MatrixXd projector =
2783 Eigen::MatrixXd::Identity(affine_full_dim_, affine_full_dim_) -
2784 basis * basis.transpose();
2785 Eigen::MatrixXd HV(m, affine_full_dim_);
2786
2787 for (Eigen::Index i = 0; i < m; ++i) {
2788 const Eigen::RowVectorXd ri = residuals.row(i);
2789 const Eigen::RowVectorXd dri = residual_directions.row(i);
2790 const double scale = std::exp(-ri.squaredNorm());
2791 const double dscale = -2.0 * scale * ri.dot(dri);
2792
2793 const double base_value = Phi_s.row(i).dot(base_coeff);
2794 Eigen::RowVectorXd base_grad = Eigen::RowVectorXd::Zero(dim_);
2795 Eigen::RowVectorXd base_hv = Eigen::RowVectorXd::Zero(dim_);
2796 for (int k = 0; k < dim_; ++k) {
2797 base_grad(k) = dPhi_s[k].row(i).dot(base_coeff);
2798 base_hv(k) = d2PhiDirection_s[k].row(i).dot(base_coeff);
2799 }
2800 const double dbase_value = base_grad.dot(tangent_directions.row(i));
2801
2802 Eigen::VectorXd normal_values(affine_full_dim_);
2803 Eigen::VectorXd dnormal_values(affine_full_dim_);
2804 Eigen::MatrixXd normal_grad =
2805 Eigen::MatrixXd::Zero(affine_full_dim_, dim_);
2806 Eigen::MatrixXd normal_hv =
2807 Eigen::MatrixXd::Zero(affine_full_dim_, dim_);
2808 for (Eigen::Index p = 0; p < affine_full_dim_; ++p) {
2809 const Eigen::VectorXd normal_coeff = coeff.segment((p + 1) * N, N);
2810 normal_values(p) = Phi_s.row(i).dot(normal_coeff);
2811 for (int k = 0; k < dim_; ++k) {
2812 normal_grad(p, k) = dPhi_s[k].row(i).dot(normal_coeff);
2813 normal_hv(p, k) = d2PhiDirection_s[k].row(i).dot(normal_coeff);
2814 }
2815 dnormal_values(p) =
2816 normal_grad.row(p).dot(tangent_directions.row(i));
2817 }
2818
2819 Eigen::RowVectorXd gu_arg = base_grad;
2820 Eigen::RowVectorXd dgu_arg = base_hv;
2821 for (Eigen::Index p = 0; p < affine_full_dim_; ++p) {
2822 gu_arg += sqrt2 * ri(p) * normal_grad.row(p);
2823 dgu_arg += sqrt2 *
2824 (dri(p) * normal_grad.row(p) + ri(p) * normal_hv.row(p));
2825 }
2826 const Eigen::RowVectorXd dgu = dscale * gu_arg + scale * dgu_arg;
2827
2828 const double normal_dot = ri.dot(normal_values);
2829 const double dnormal_dot =
2830 dri.dot(normal_values) + ri.dot(dnormal_values);
2831 const double h = base_value + sqrt2 * normal_dot;
2832 const double dh = dbase_value + sqrt2 * dnormal_dot;
2833
2834 Eigen::RowVectorXd gr_arg(affine_full_dim_);
2835 Eigen::RowVectorXd dgr_arg(affine_full_dim_);
2836 for (Eigen::Index p = 0; p < affine_full_dim_; ++p) {
2837 gr_arg(p) = -2.0 * ri(p) * h + sqrt2 * normal_values(p);
2838 dgr_arg(p) = -2.0 * dri(p) * h - 2.0 * ri(p) * dh +
2839 sqrt2 * dnormal_values(p);
2840 }
2841 const Eigen::RowVectorXd dgr = dscale * gr_arg + scale * dgr_arg;
2842 HV.row(i) = dgu * basis.transpose() + dgr * projector;
2843 }
2844 return HV;
2845}

◆ projectToAffineSpan()

void gpr::StableBasisND::projectToAffineSpan ( const Eigen::MatrixXd & centered_X,
const Eigen::MatrixXd & basis,
Eigen::MatrixXd & coords,
Eigen::MatrixXd & residuals )
static

Definition at line 1842 of file StableBasis.cpp.

1846{
1847 coords = centered_X * basis;
1848 residuals = centered_X - coords * basis.transpose();
1849}

◆ rangeVarianceFromDesignForTesting()

Eigen::VectorXd gpr::StableBasisND::rangeVarianceFromDesignForTesting ( const Eigen::MatrixXd & A_E,
double sigma2 ) const
nodiscard

The design variance of the rows of A_E at sigma2, and the retained training design it contracts against.

Definition at line 4805 of file StableBasis.cpp.

4807{
4808 return rangeVarianceFromDesign(A_E, sigma2);
4809}

◆ rank()

int gpr::StableBasisND::rank ( ) const
inline

Definition at line 824 of file StableBasis.h.

825 {
826 return rank_;
827 }

◆ reconstructKernel()

Eigen::MatrixXd gpr::StableBasisND::reconstructKernel ( bool truncated) const

Definition at line 4722 of file StableBasis.cpp.

4723{
4724 if (truncated) {
4725 if (Psi_.size() == 0 || Sr_.size() == 0) return Eigen::MatrixXd();
4726 // K_trunc = Psi diag(S^2) Psi^T (the rank-kept kernel solveNoisy uses).
4727 return Psi_ * Sr_.array().square().matrix().asDiagonal() *
4728 Psi_.transpose();
4729 }
4730 // K_exact = A_full A_full^T (the full Mercer Gram at this max_degree).
4731 if (A_train_.size() == 0) return Eigen::MatrixXd();
4732 return A_train_ * A_train_.transpose();
4733}

◆ recordDroppedSpectrum()

void gpr::StableBasisND::recordDroppedSpectrum ( const Eigen::VectorXd & S)

Definition at line 996 of file StableBasis.cpp.

997{
998 // Largest eigenvalue s^2 the truncation discarded: the exact weight of a
999 // discarded component in (K + sigma2 I)^-1 lies in
1000 // [1/(dropped_s2_max_ + sigma2), 1/sigma2]; the posterior formulas use
1001 // the lower end, which never overshoots the explicit posterior and is
1002 // exact to dropped_s2_max_/sigma2 relative (eps s2_max/sigma2 for the
1003 // resolution cutoff).
1004 //
1005 // A dropped eigenvalue below the eigensolver's backward error n eps s2_max
1006 // is rounding, not spectrum: its size and sign change with the solver,
1007 // and a weight 1/(s2 + sigma2) built on it moves every posterior
1008 // quantity by s2/sigma2 relative from one evaluation to the next. Such a
1009 // direction is null, and its weight is 1/sigma2.
1010 dropped_s2_max_ = 0.0;
1011 if (rank_ >= 0 && rank_ < S.size()) {
1012 const double s = S(rank_);
1013 const double s2 = std::isfinite(s) ? s * s : 0.0;
1014 const double s2_max =
1015 S.size() > 0 && std::isfinite(S(0)) ? S(0) * S(0) : 0.0;
1016 const double resolution =
1017 static_cast<double>(std::max<Eigen::Index>(1, S.size())) *
1018 std::numeric_limits<double>::epsilon() * s2_max;
1019 dropped_s2_max_ = s2 > resolution ? s2 : 0.0;
1020 }
1021}

◆ resetSchurFloorTotals()

void gpr::StableBasisND::resetSchurFloorTotals ( )
staticnoexcept

Definition at line 4834 of file StableBasis.cpp.

4835{
4836 g_schur_floored.store(0, std::memory_order_relaxed);
4837 g_schur_proven_negative.store(0, std::memory_order_relaxed);
4838 g_schur_uncertified.store(0, std::memory_order_relaxed);
4839 g_schur_raised.store(0, std::memory_order_relaxed);
4840}

◆ schurFloorTotals()

StableBasisND::SchurFloorReport gpr::StableBasisND::schurFloorTotals ( )
staticnodiscardnoexcept

Process-wide totals of SchurFloorReport over every call.

Definition at line 4823 of file StableBasis.cpp.

4824{
4825 SchurFloorReport totals;
4826 totals.floored = g_schur_floored.load(std::memory_order_relaxed);
4827 totals.proven_negative =
4828 g_schur_proven_negative.load(std::memory_order_relaxed);
4829 totals.uncertified = g_schur_uncertified.load(std::memory_order_relaxed);
4830 totals.raised = g_schur_raised.load(std::memory_order_relaxed);
4831 return totals;
4832}

◆ setChopNoiseVariance()

void gpr::StableBasisND::setChopNoiseVariance ( double sigma2)
inlinenoexcept

Likelihood variance (noise + jitter) the plateau chop must respect: a component with s^2 > chop_tol * sigma2 is never dropped, because its removal perturbs (K + sigma2 I)^-1 by s^2/sigma2 relative.

Definition at line 202 of file StableBasis.h.

203 {
204 chop_sigma2_ = sigma2;
205 }

◆ setRetainedSpectrumForTesting()

void gpr::StableBasisND::setRetainedSpectrumForTesting ( Eigen::MatrixXd psi,
Eigen::VectorXd singular_values )
inline

Install a caller-built retained basis and spectrum, so a test can give the projection a basis whose columns have lost orthogonality. Only the range variance reductions, which read Psi_ and Sr_, are meaningful afterwards; every cached factorization is dropped.

Definition at line 867 of file StableBasis.h.

869 {
870 if (psi.cols() != singular_values.size())
871 throw std::invalid_argument(
872 "retained basis and spectrum must have the same rank");
873 Psi_ = std::move(psi);
874 Sr_ = std::move(singular_values);
875 rank_ = static_cast<int>(Sr_.size());
876 dropped_s2_max_ = 0.0;
877 noisy_eigvals_.resize(0);
878 clearBorderedCache();
879 }

◆ singularValues()

const Eigen::VectorXd & gpr::StableBasisND::singularValues ( ) const
inline

Definition at line 954 of file StableBasis.h.

955 {
956 return Sr_;
957 }

◆ solve()

Eigen::VectorXd gpr::StableBasisND::solve ( const Eigen::VectorXd & y) const

Definition at line 2619 of file StableBasis.cpp.

2620{
2621 return Psi_.colPivHouseholderQr().solve(y);
2622}

◆ solveNoisy()

Eigen::VectorXd gpr::StableBasisND::solveNoisy ( const Eigen::VectorXd & y,
double sigma2 ) const

Definition at line 3079 of file StableBasis.cpp.

3081{
3082 sigma2 = conditionFlooredSigma2(Sr_, sigma2, Psi_.rows());
3083 // (K + sigma2 I)^{-1} y with K = Psi diag(S^2) Psi^T (Psi orthonormal):
3084 // = Psi diag(1/(S^2+sigma2)) (Psi^T y) + (1/sigma2)(y - Psi (Psi^T y)).
3085 // mu_i = S_i^2 + sigma2; the noisy-objective path stores mu_i directly so
3086 // the inverse avoids the cancelling sum S_i^2 + sigma2.
3087 const Eigen::VectorXd p = Psi_.transpose() * y; // rank
3088 const Eigen::ArrayXd mu =
3089 hasNoisyEigenvalues() ? Eigen::ArrayXd(noisy_eigvals_.array())
3090 : Eigen::ArrayXd(Sr_.array().square() + sigma2);
3091 const Eigen::ArrayXd d = mu.inverse();
3092 Eigen::VectorXd solved = Psi_ * (d.matrix().asDiagonal() * p);
3093 const double complement = complementWeight(sigma2);
3094 if (complement > 0.0) {
3095 solved += complement * (y - Psi_ * p);
3096 }
3097 return solved;
3098}

◆ stableRangePosteriorDiagonal()

Eigen::VectorXd gpr::StableBasisND::stableRangePosteriorDiagonal ( const Eigen::MatrixXd & rhs,
const Eigen::VectorXd & prior,
const Eigen::VectorXd & signal,
double sigma2,
bool check_variance = true ) const

Range-only posterior diagonal as a nonnegative eigenmode sum.

The value is prior_j - z_j^T diag(1/(S^2+sigma2)) z_j with z_j = Psi^T rhs_j, the contraction noisyRangeSelfQuadratic subtracts, evaluated as the unresolved tail prior_j - norm(S^-1 z_j)^2 plus the noise-damped terms sigma2/(S^2+sigma2) (S^-1 z_j)^2 in ExactSum. signal_j is the variance of the diagonal that entered the sum and sets the roundoff allowance of linalg::requireStablePosteriorVariance. sigma2 is floored through varianceFlooredNoise. A shape mismatch or a non-positive noise floor throws linalg::StableVarianceError. Callers that replace training-row channels with their latent identity defer the finite/nonnegative check until after that replacement.

Definition at line 3149 of file StableBasis.cpp.

3152{
3153 if (prior.size() != rhs.cols() || signal.size() != prior.size())
3154 throw linalg::StableVarianceError(
3155 "stable range posterior variance: prior, signal and query "
3156 "columns disagree");
3157 if (rhs.rows() != Psi_.rows() || Psi_.cols() != Sr_.size())
3158 throw linalg::StableVarianceError(
3159 "stable range posterior variance: cross covariance does not match "
3160 "the stable basis");
3161 sigma2 = varianceFlooredSigma2(Sr_, sigma2, Psi_.rows());
3162 if (!(sigma2 > 0.0) || !std::isfinite(sigma2))
3163 throw linalg::StableVarianceError(
3164 "stable range posterior variance: noise floor is not finite and "
3165 "positive");
3166 Eigen::VectorXd variance(rhs.cols());
3167 if (rhs.cols() == 0) return variance;
3168 Eigen::MatrixXd projected, residual;
3169 projectOntoStableBasis(Psi_, rhs, projected, residual);
3170 const Eigen::VectorXd no_residual;
3171 for (Eigen::Index column = 0; column < rhs.cols(); ++column) {
3172 linalg::ExactSum local_prior;
3173 local_prior.add(prior(column));
3174 variance(column) = nonnegativeEigenmodeVariance(
3175 projected.col(column), no_residual, Sr_, sigma2, 0.0,
3176 /*use_complement=*/false, local_prior);
3177 if (check_variance)
3179 signal(column));
3180 }
3181 return variance;
3182}
void requireStablePosteriorVariance(double &variance, double signal_variance, double relative_allowance)
Accept one stable posterior variance or throw.
Definition ExactSchur.h:131

◆ standardChop()

Eigen::Index gpr::StableBasisND::standardChop ( const Eigen::VectorXd & coeffs,
double tol )
static

Definition at line 871 of file StableBasis.cpp.

873{
874 // Port of the Aurentz-Trefethen standardChop algorithm
875 // (doi:10.1145/2998442). Indices are kept 1-based to match the paper;
876 // returns the count of leading entries to retain, or coeffs.size() when no
877 // plateau is found.
878 const int n = static_cast<int>(coeffs.size());
879 if (tol >= 1.0) return 1;
880 if (n < 17) return n;
881 // Step 1: monotone-nonincreasing envelope, normalized to begin at 1.
882 std::vector<double> m(n + 1, 0.0);
883 m[n] = std::abs(coeffs(n - 1));
884 for (int j = n - 1; j >= 1; --j)
885 m[j] = std::max(std::abs(coeffs(j - 1)), m[j + 1]);
886 if (m[1] == 0.0) return 1;
887 std::vector<double> env(n + 1, 0.0);
888 for (int j = 1; j <= n; ++j)
889 env[j] = m[j] / m[1];
890 // Step 2: scan for a plateau point.
891 int plateauPoint = 0, j2 = 0;
892 bool found = false;
893 for (int j = 2; j <= n; ++j) {
894 j2 = static_cast<int>(std::round(1.25 * j + 5.0));
895 if (j2 > n) return n; // no plateau -> not happy
896 const double e1 = env[j], e2 = env[j2];
897 const double r = 3.0 * (1.0 - std::log(e1) / std::log(tol));
898 if (e1 == 0.0 || e2 / e1 > r) {
899 plateauPoint = j - 1;
900 found = true;
901 break;
902 }
903 }
904 if (!found) return n;
905 // Step 3: refine the cutoff with a left-biasing linear tilt.
906 if (env[plateauPoint] == 0.0) return std::max(plateauPoint, 1);
907 const double t76 = std::pow(tol, 7.0 / 6.0);
908 int j3 = 0;
909 for (int j = 1; j <= n; ++j)
910 if (env[j] >= t76) ++j3;
911 if (j3 < j2) {
912 j2 = j3 + 1;
913 if (j2 <= n) env[j2] = t76;
914 }
915 const double slope = (-1.0 / 3.0) * std::log10(tol);
916 int dmin = 1;
917 double best = std::numeric_limits<double>::infinity();
918 for (int j = 1; j <= j2; ++j) {
919 const double lin = (j2 > 1) ? slope * static_cast<double>(j - 1) /
920 static_cast<double>(j2 - 1)
921 : 0.0;
922 const double cc = std::log10(env[j]) + lin;
923 if (cc < best) {
924 best = cc;
925 dmin = j;
926 }
927 }
928 return std::max(dmin - 1, 1);
929}

◆ supportsBorderedVarianceInterval()

bool gpr::StableBasisND::supportsBorderedVarianceInterval ( ) const
inlinenodiscardnoexcept

Whether this factorization retained the exact assembled kernel needed by noisyBorderedVarianceIntervals. Design-only factorizations are not eligible for certification.

Definition at line 616 of file StableBasis.h.

617 {
618 const Eigen::Index expected = borderedKernelOrder();
619 return bordered_kernel_.rows() == expected &&
620 bordered_kernel_.cols() == expected;
621 }
Eigen::Index borderedKernelOrder() const noexcept

◆ trainingDesignForTesting()

const Eigen::MatrixXd & gpr::StableBasisND::trainingDesignForTesting ( ) const
inlinenodiscard

Definition at line 916 of file StableBasis.h.

917 {
918 return A_train_;
919 }

◆ trainingRowLatentErrorBound()

double gpr::StableBasisND::trainingRowLatentErrorBound ( Eigen::Index row,
double sigma2 ) const
nodiscard

Upper bound on the binary64 rounding error of the training-row latent variance eta2 - eta2^2 q(row), q the diagonal of (K_r + eta2 I)^-1 assembled from the retained spectrum. It includes the departure of the retained row from unit norm, which the nonnegativity of the latent variance assumes. Infinite when it cannot be bounded.

Definition at line 4915 of file StableBasis.cpp.

4917{
4918 using Extended = gpr::extended::WorkingReal;
4919 const double inf = std::numeric_limits<double>::infinity();
4920 if (row < 0 || row >= Psi_.rows() || Psi_.cols() != Sr_.size() ||
4921 !(statistical_sigma2 > 0.0) || !std::isfinite(statistical_sigma2))
4922 return inf;
4923 try {
4924 const Eigen::Index rank = Psi_.cols();
4925 const Extended eta2(statistical_sigma2);
4926 const Extended complement(
4927 covarianceComplementWeight(statistical_sigma2));
4928 Extended sum = complement;
4929 Extended row_norm2 = 0;
4930 for (Eigen::Index k = 0; k < rank; ++k) {
4931 const Extended psi = static_cast<Extended>(Psi_(row, k));
4932 const Extended s = static_cast<Extended>(Sr_(k));
4933 const Extended psi2 = psi * psi;
4934 const Extended inverse = Extended(1) / (s * s + eta2);
4935 sum += psi2 * (inverse + complement);
4936 row_norm2 += psi2;
4937 }
4938 // Magnitude of every term of eta2 - eta2^2 q. Each double operation
4939 // on a term costs at most one unit roundoff of that term, and a term
4940 // passes through latentVarianceOperationDepth(rank) of them.
4941 const long long ops = latentVarianceOperationDepth(rank);
4942 const Extended magnitude = directedUpper(
4943 eta2 + eta2 * eta2 * sum, latentMagnitudeOperationDepth(rank));
4944 const Extended unit(std::ldexp(1.0, -53));
4945 const Extended order = static_cast<Extended>(ops);
4946 if (!(order * unit < Extended(1))) return inf;
4947 const Extended gamma =
4948 directedUpper((order * unit) / (Extended(1) - order * unit), 4);
4949 Extended bound = directedUpper(gamma * magnitude, 1);
4950 // The latent variance is eta2 (1 - eta2 w_c)(1 - ||psi_row||^2) plus
4951 // nonnegative terms, so a retained row longer than 1 by delta lets
4952 // it fall below zero by at most eta2 delta.
4953 const Extended norm2 =
4954 directedUpper(row_norm2, 2 * static_cast<long long>(rank) + 2);
4955 if (norm2 > Extended(1))
4956 bound = directedUpper(bound + eta2 * (norm2 - Extended(1)), 3);
4957 if (!gpr::extended::workingFinite(bound)) return inf;
4958 return gpr::extended::roundUpToDouble(bound);
4959 } catch (const BorderedVarianceError&) {
4960 return inf;
4961 }
4962}
double covarianceComplementWeight(double sigma2) const noexcept
bool workingFinite(Work value)

◆ usedFastKernelEigensolverForTesting()

bool gpr::StableBasisND::usedFastKernelEigensolverForTesting ( ) const
inlinenoexcept

Definition at line 850 of file StableBasis.h.

851 {
852 return fast_kernel_eigensolver_used_;
853 }

◆ usedLapackRrrValueRange()

bool gpr::StableBasisND::usedLapackRrrValueRange ( ) const
inlinenoexcept

Definition at line 828 of file StableBasis.h.

829 {
830 return lapack_rrr_value_range_used_;
831 }

◆ usedLapackRrrValueRangeForTesting()

bool gpr::StableBasisND::usedLapackRrrValueRangeForTesting ( ) const
inlinenoexcept

Definition at line 846 of file StableBasis.h.

847 {
849 }
bool usedLapackRrrValueRange() const noexcept

◆ varianceFlooredNoise()

double gpr::StableBasisND::varianceFlooredNoise ( double sigma2) const
nodiscard

Variance-specific likelihood-noise floor for the retained spectrum.

With the stable posterior variance on, the floor resolves one squared eigenvalue to eps*s2_max and does not grow with the observation count, because the stable variances are nonnegative eigenmode sums reduced exactly. Inverse, mean, log-determinant, LOO and the training-row identity keep conditionFlooredNoise, the n*eps floor of their rounded observation-space projector. With the option off this equals conditionFlooredNoise.

Definition at line 3037 of file StableBasis.cpp.

3038{
3039 return varianceFlooredSigma2(Sr_, sigma2, Psi_.rows());
3040}

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