11#include <Eigen/Eigenvalues>
39void dsyevr_(
char*,
char*,
char*,
int*,
double*,
int*,
double*,
double*,
int*,
40 int*,
double*,
int*,
double*,
double*,
int*,
int*,
double*,
int*,
46Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> timedSymmetricEigen(
47 const Eigen::MatrixXd& matrix)
49 const auto start = std::chrono::steady_clock::now();
50 Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> solver(matrix);
52 std::chrono::duration<double>(std::chrono::steady_clock::now() - start)
59#ifdef GPR_LINALG_SCALAPACK
68bool useGpuEigensolverForProcessCount(
int process_count)
noexcept
70 return process_count == 1;
73bool useRankBlockKernelAppend(
bool gpu_full_eigensolver_available)
noexcept
75 return !gpu_full_eigensolver_available;
82class BorderedVarianceError :
public std::runtime_error {
84 using std::runtime_error::runtime_error;
102bool workingIsFinite(T value)
111constexpr int kAssemblyPairOps = 1;
129constexpr int kEpsKSumAdditions = 5;
130constexpr int kEpsPosOps = 5;
131constexpr int kEpsQrExtraOps = 3;
132constexpr int kEpsBbExtraOps = 1;
134constexpr int kFormedFactorEntryOps = 3;
135constexpr int kLambdaCertMulOps = 4;
136constexpr int kMuMinOps = 3;
137constexpr int kESplitQOps = 10;
138constexpr int kESolveQOps = 7;
139constexpr int kQtVErrOps = 3;
140constexpr int kEOrthQOps = 12;
141constexpr int kESumOps = 4;
142constexpr int kEKernelOps = 1;
143constexpr int kEQHiSumOps = 4;
144constexpr int kRNormOps = 13;
145constexpr int kSquareOps = 1;
146constexpr int kResDivOps = 1;
147constexpr int kELowerAddOps = 1;
149template <
typename Extended>
150Extended directedGamma(
long long expression_ops)
152 using Prec = gpr::extended::WorkingPrecision<Extended>;
157 if (total <= 0 || total > (1LL << 53))
158 throw BorderedVarianceError(
159 "the directed margin exceeds working-precision resolution");
160 const Extended k(
static_cast<double>(total));
161 const Extended u = Prec::unitRoundoff();
162 if (!(k * u < Extended(1)))
163 throw BorderedVarianceError(
164 "the directed margin exceeds working-precision resolution");
165 return (k * u) / (Extended(1) - k * u);
170template <
typename Extended>
171Extended directedUpper(Extended value,
long long expression_ops)
173 using Prec = gpr::extended::WorkingPrecision<Extended>;
174 if (!workingIsFinite(value))
175 throw BorderedVarianceError(
176 "the bordered variance error bound is not finite");
177 if (!(value > Extended(0)))
return Extended(0);
178 const Extended gamma = directedGamma<Extended>(expression_ops);
179 return Prec::nextUp(value * (Extended(1) + gamma));
184template <
typename Extended>
185Extended directedLower(Extended value,
long long expression_ops)
187 using Prec = gpr::extended::WorkingPrecision<Extended>;
188 if (!workingIsFinite(value) || !(value > Extended(0)))
return Extended(0);
189 const Extended gamma = directedGamma<Extended>(expression_ops);
190 Extended scaled = value * (Extended(1) - gamma);
191 if (!(scaled > Extended(0)))
return Extended(0);
192 scaled = Prec::nextDown(scaled);
193 return (scaled > Extended(0)) ? scaled : Extended(0);
199long long gramResidualEntryOps(Eigen::Index rank)
201 const long long width =
static_cast<long long>(rank);
202 if (width > (1LL << 26))
203 throw BorderedVarianceError(
204 "the bordered factor order exceeds the residual operation count");
205 return 2 * width + 1;
208double kernelAssemblyErrorBound(
const Eigen::MatrixXd& kernel,
209 const Eigen::MatrixXd& symmetric)
212 const Extended unit =
213 gpr::extended::WorkingPrecision<Extended>::unitRoundoff();
214 const Extended order =
static_cast<Extended
>(kernel.cols());
215 if (!(order * unit < Extended(1)))
216 throw BorderedVarianceError(
217 "the kernel order exceeds assembly-bound resolution");
218 const Extended inflation = Extended(1) / (Extended(1) - order * unit);
220 for (Eigen::Index row = 0; row < kernel.rows(); ++row) {
221 Extended row_sum = 0;
222 for (Eigen::Index col = 0; col < kernel.cols(); ++col) {
223 row_sum += workingAbs(
static_cast<Extended
>(symmetric(row, col)) -
224 static_cast<Extended
>(kernel(row, col)));
226 const Extended row_bound = inflation * row_sum;
227 if (row_bound > bound) bound = row_bound;
236template <
typename Computed,
typename AbsTerms>
238 const AbsTerms& abs_terms,
243 computed, abs_terms, entry_ops);
244 if (!workingIsFinite(bound)) {
245 throw BorderedVarianceError(
246 "the bordered residual bound exceeds working-precision "
252void validateJointJacobians(
const Eigen::MatrixXd& points,
253 const std::vector<Eigen::MatrixXd>& jacobians)
255 if (points.rows() <= 0 ||
256 jacobians.size() !=
static_cast<std::size_t
>(points.rows())) {
257 throw std::invalid_argument(
258 "joint factorization requires one Jacobian per observation");
260 Eigen::Index gradient_components = -1;
261 for (
const Eigen::MatrixXd& jacobian: jacobians) {
262 if (jacobian.rows() != points.cols() || jacobian.cols() <= 0) {
263 throw std::invalid_argument(
264 "joint factorization requires complete gradient channels");
266 if (gradient_components < 0) {
267 gradient_components = jacobian.cols();
268 }
else if (jacobian.cols() != gradient_components) {
269 throw std::invalid_argument(
270 "joint observations require a common gradient dimension");
275void validateJointAffineJacobians(
276 const Eigen::MatrixXd& coordinates,
277 const std::vector<Eigen::MatrixXd>& tangent_jacobians,
278 const std::vector<Eigen::MatrixXd>& normal_jacobians)
280 validateJointJacobians(coordinates, tangent_jacobians);
281 if (normal_jacobians.size() != tangent_jacobians.size()) {
282 throw std::invalid_argument(
283 "affine joint factorization requires tangent and normal "
286 const Eigen::Index gradient_components = tangent_jacobians[0].cols();
287 const Eigen::Index normal_dimension = normal_jacobians[0].rows();
288 for (
const Eigen::MatrixXd& jacobian: normal_jacobians) {
289 if (jacobian.rows() != normal_dimension ||
290 jacobian.cols() != gradient_components) {
291 throw std::invalid_argument(
292 "affine joint Jacobians must share observation dimensions");
301double singularCutoff(
const Eigen::VectorXd& S,
double sv_rtol,
304 if (S.size() == 0)
return 0.0;
305 return std::max(sv_rtol * S(0), sv_abs_tol);
308double dualKernelSingularCutoff(
const Eigen::VectorXd& S,
double sv_rtol,
311 double cutoff = singularCutoff(S, sv_rtol, sv_abs_tol);
312 if (S.size() == 0)
return cutoff;
314 const double s0 = std::abs(S(0));
316 static_cast<double>(S.size()) * std::numeric_limits<double>::epsilon();
317 if (std::isfinite(s0) && s0 > 0.0 && neps > 0.0 && neps < 1.0) {
323 const double gamma_n = neps / (1.0 - neps);
324 cutoff = std::max(cutoff, std::sqrt(gamma_n) * s0);
329Eigen::Index keptSingularRank(
const Eigen::VectorXd& S,
double cutoff)
334Eigen::Index keptSingularRankWithChop(
const Eigen::VectorXd& S,
double cutoff,
335 double chop_tol,
double sigma2)
337 Eigen::Index rank = keptSingularRank(S, cutoff);
338 if (rank <= 0 || !(chop_tol > 0.0 && chop_tol < 1.0))
return rank;
340 if (chopped <= 0)
return rank;
341 Eigen::Index kept = std::min(rank, chopped);
349 if (sigma2 > 0.0 && std::isfinite(sigma2)) {
350 const double keep_below = chop_tol * sigma2;
351 while (kept < rank && S(kept) * S(kept) > keep_below)
357Eigen::ArrayXd stablePosteriorShrinkage(
const Eigen::ArrayXd& signal_eigvals,
358 double sigma2, Eigen::Index nobs)
360 Eigen::ArrayXd shrink = signal_eigvals / (signal_eigvals + sigma2);
361 if (shrink.size() <= 1 || !(sigma2 > 0.0))
return shrink;
363 const double neps =
static_cast<double>(std::max<Eigen::Index>(1, nobs)) *
364 std::numeric_limits<double>::epsilon();
365 if (!(neps > 0.0 && neps < 1.0))
return shrink;
366 const double gamma_n = neps / (1.0 - neps);
367 const double eigengap_tol = std::sqrt(gamma_n);
369 Eigen::Index first = 0;
370 while (first < shrink.size()) {
371 Eigen::Index last = first + 1;
372 double lo = signal_eigvals(first);
373 double hi = signal_eigvals(first);
374 while (last < shrink.size()) {
375 const double candidate = signal_eigvals(last);
376 const double next_lo = std::min(lo, candidate);
377 const double next_hi = std::max(hi, candidate);
378 const double scale = std::max(std::abs(next_lo), std::abs(next_hi));
379 if (scale <= 0.0 || next_hi - next_lo > eigengap_tol * scale)
break;
384 if (last - first > 1) {
385 const double block = shrink.segment(first, last - first).mean();
386 shrink.segment(first, last - first).setConstant(block);
393double symmetricEigenUpperBound(
const Eigen::MatrixXd& sym)
395 if (sym.rows() != sym.cols())
396 return std::numeric_limits<double>::quiet_NaN();
397 if (sym.rows() == 0)
return 0.0;
399 double upper = -std::numeric_limits<double>::infinity();
400 for (Eigen::Index i = 0; i < sym.rows(); ++i) {
402 for (Eigen::Index j = 0; j < sym.cols(); ++j) {
403 if (i == j)
continue;
404 radius += std::abs(sym(i, j));
406 upper = std::max(upper, sym(i, i) + radius);
408 if (!std::isfinite(upper))
return upper;
409 return std::nextafter(std::max(0.0, upper),
410 std::numeric_limits<double>::infinity());
418bool hostSymmetricEigenpairs(
const Eigen::MatrixXd& sym, Eigen::VectorXd& evals,
419 Eigen::MatrixXd& evecs)
428bool hostSymmetricEigenpairsAbove(
const Eigen::MatrixXd& sym,
double min_eval,
429 Eigen::VectorXd& evals,
430 Eigen::MatrixXd& evecs)
432 if (sym.rows() != sym.cols())
return false;
433 if (!(min_eval >= 0.0) || !std::isfinite(min_eval))
return false;
434 if (sym.rows() == 0) {
439 const double upper = symmetricEigenUpperBound(sym);
440 if (!(std::isfinite(upper) && upper > min_eval))
return false;
441 Eigen::VectorXd all_evals;
442 Eigen::MatrixXd all_evecs;
443 if (!hostSymmetricEigenpairs(sym, all_evals, all_evecs))
return false;
444 Eigen::Index keep = 0;
445 for (Eigen::Index i = 0; i < all_evals.size(); ++i)
446 if (all_evals(i) > min_eval) ++keep;
447 evals = all_evals.tail(keep);
448 evecs = all_evecs.rightCols(keep);
466bool reproducibleBasis() noexcept
474 return detail::useGpuEigensolverForProcessCount(process_group.nprocs);
480 if (reproducibleBasis() || !gpuEighUsableInProcess(process_group))
483 return cusolver.available() ? &cusolver :
nullptr;
515 const Eigen::MatrixXd& sym,
516 Eigen::VectorXd& evals_asc,
517 Eigen::MatrixXd& evecs_asc,
const char** driver_name)
519#ifdef GPR_LINALG_SCALAPACK
520 auto& st = context.distributed();
525 context.distributed_symmetric_eigen(sym, evals_asc, evecs_asc,
530 if (driver_name !=
nullptr) *driver_name =
"serial_floor";
535 const Eigen::MatrixXd& sym, Eigen::VectorXd& evals,
536 Eigen::MatrixXd& evecs,
537 const char** driver_name =
nullptr)
539 const auto eigen_start = std::chrono::steady_clock::now();
540 const auto note_eigen = [&]() {
542 std::chrono::duration<double>(std::chrono::steady_clock::now() -
546 if (reproducibleBasis()) {
547 const bool solved = hostSymmetricEigenpairs(sym, evals, evecs);
548 if (solved && driver_name !=
nullptr)
549 *driver_name =
"eigen_selfadjoint";
553 auto* cusolver = availableGpuEigensolver(process_group);
554 if (cusolver && cusolver->allEigenpairs(sym, evals, evecs)) {
555 if (driver_name !=
nullptr) *driver_name =
"cusolver_syevd";
559 const bool valid = hostSymmetricEigenpairs(sym, evals, evecs);
560 if (valid && driver_name !=
nullptr) *driver_name =
"eigen_selfadjoint";
570 const Eigen::MatrixXd& sym,
double min_eval,
571 Eigen::VectorXd& evals, Eigen::MatrixXd& evecs,
572 const char** driver_name =
nullptr)
574 if (reproducibleBasis()) {
576 hostSymmetricEigenpairsAbove(sym, min_eval, evals, evecs);
577 if (valid && driver_name !=
nullptr) *driver_name =
"eigen_selfadjoint";
580 auto* cusolver = availableGpuEigensolver(process_group);
582 Eigen::VectorXd all_evals;
583 Eigen::MatrixXd all_evecs;
584 if (cusolver->allEigenpairs(sym, all_evals, all_evecs)) {
585 Eigen::Index keep = 0;
586 for (Eigen::Index i = 0; i < all_evals.size(); ++i)
587 if (all_evals(i) > min_eval) ++keep;
589 evecs.resize(all_evecs.rows(), keep);
591 for (Eigen::Index i = 0; i < all_evals.size(); ++i) {
592 if (all_evals(i) > min_eval) {
593 evals(c) = all_evals(i);
594 evecs.col(c) = all_evecs.col(i);
598 if (driver_name !=
nullptr) *driver_name =
"cusolver_syevd";
603 hostSymmetricEigenpairsAbove(sym, min_eval, evals, evecs);
604 if (valid && driver_name !=
nullptr) *driver_name =
"eigen_selfadjoint";
612 Eigen::MatrixXd& evecs)
614 return hostSymmetricEigenpairs(sym, evals, evecs);
618bool detail::gpuFullKernelEigensolverAvailable() noexcept
620 return gpuFullKernelEigensolverAvailable(linalg::BackendContext{}.mpi());
623bool detail::gpuFullKernelEigensolverAvailable(
626 return availableGpuEigensolver(process_group) !=
nullptr;
630 : backend_context_(
std::make_shared<
linalg::BackendContext>())
635 : backend_context_(
std::move(context))
637 if (!backend_context_)
638 throw std::invalid_argument(
"stable basis requires a backend context");
641Eigen::MatrixXd StableBasis1D::eigenfunctions(
const Eigen::VectorXd&
x)
const
651 const Eigen::Index m =
x.size();
652 Eigen::MatrixXd Phi(m, N_);
653 if (N_ <= 0)
return Phi;
654 const Eigen::ArrayXd u = (alpha_ * beta_) *
x.array();
655 const Eigen::ArrayXd env = (-delta2_ *
x.array().square()).exp();
656 const double sb = std::sqrt(beta_);
658 Eigen::ArrayXd psi_prev = Eigen::ArrayXd::Constant(m, sb);
659 Phi.col(0) = (env * psi_prev).matrix();
661 Eigen::ArrayXd psi_cur = std::sqrt(2.0) * sb * u;
662 Phi.col(1) = (env * psi_cur).matrix();
663 for (
int n = 1; n + 1 < N_; ++n) {
664 const double a = std::sqrt(2.0 / (n + 1));
665 const double b = std::sqrt(
static_cast<double>(n) / (n + 1));
666 Eigen::ArrayXd psi_next = a * (u * psi_cur) - b * psi_prev;
667 Phi.col(n + 1) = (env * psi_next).matrix();
676 const Eigen::VectorXd&
x, Eigen::MatrixXd& Phi,
677 Eigen::MatrixXd& dPhi_deps)
const
682 const Eigen::Index m =
x.size();
684 dPhi_deps.resize(m, N_);
686 const double dbeta = 2.0 * eps_ / (alpha_ * alpha_ * beta_ * beta_ * beta_);
687 const double ddelta2 = alpha_ * alpha_ * beta_ * dbeta;
688 const Eigen::ArrayXd u = (alpha_ * beta_) *
x.array();
689 const Eigen::ArrayXd du = (alpha_ * dbeta) *
x.array();
690 const Eigen::ArrayXd env = (-delta2_ *
x.array().square()).exp();
691 const Eigen::ArrayXd denv =
692 env * (-
x.array().square() * ddelta2);
693 const double sb = std::sqrt(beta_);
694 const double dsb = dbeta / (2.0 * sb);
696 Eigen::ArrayXd psi_prev = Eigen::ArrayXd::Constant(m, sb);
697 Eigen::ArrayXd dpsi_prev = Eigen::ArrayXd::Constant(m, dsb);
698 Phi.col(0) = (env * psi_prev).matrix();
699 dPhi_deps.col(0) = (denv * psi_prev + env * dpsi_prev).matrix();
701 Eigen::ArrayXd psi_cur = std::sqrt(2.0) * sb * u;
702 Eigen::ArrayXd dpsi_cur = std::sqrt(2.0) * (dsb * u + sb * du);
703 Phi.col(1) = (env * psi_cur).matrix();
704 dPhi_deps.col(1) = (denv * psi_cur + env * dpsi_cur).matrix();
705 for (
int n = 1; n + 1 < N_; ++n) {
706 const double a = std::sqrt(2.0 / (n + 1));
707 const double b = std::sqrt(
static_cast<double>(n) / (n + 1));
708 Eigen::ArrayXd psi_next = a * (u * psi_cur) - b * psi_prev;
709 Eigen::ArrayXd dpsi_next =
710 a * (du * psi_cur + u * dpsi_cur) - b * dpsi_prev;
711 Phi.col(n + 1) = (env * psi_next).matrix();
712 dPhi_deps.col(n + 1) = (denv * psi_next + env * dpsi_next).matrix();
715 dpsi_prev = dpsi_cur;
716 dpsi_cur = dpsi_next;
723 Eigen::VectorXd
out(N_);
724 if (N_ <= 0)
return out;
725 const double dbeta = 2.0 * eps_ / (alpha_ * alpha_ * beta_ * beta_ * beta_);
726 const double ddelta2 = alpha_ * alpha_ * beta_ * dbeta;
727 const double denom = alpha_ * alpha_ + delta2_ + eps_ * eps_;
728 const double ddenom = ddelta2 + 2.0 * eps_;
729 const double lam0 = std::sqrt(alpha_ * alpha_ / denom);
730 const double r = eps_ * eps_ / denom;
731 const double dlam0 = -alpha_ * ddenom / (2.0 * std::pow(denom, 1.5));
733 (2.0 * eps_ * denom - eps_ * eps_ * ddenom) / (denom * denom);
734 for (
int n = 0; n < N_; ++n) {
735 out(n) = sqrt_lam_(n) * (dlam0 / (2.0 * lam0) +
736 static_cast<double>(n) * dr / (2.0 * r));
742 double alpha,
int n_extra,
double sv_rtol)
746 M_ =
static_cast<int>(
x.size());
750 beta_ = std::pow(1.0 + std::pow(2.0 * eps / alpha, 2), 0.25);
751 delta2_ = alpha * alpha / 2.0 * (beta_ * beta_ - 1.0);
752 const double denom = alpha * alpha + delta2_ + eps * eps;
753 const double r = eps * eps / denom;
754 const double lam0 = std::sqrt(alpha * alpha / denom);
756 sqrt_lam_.resize(N_);
757 const double sqrt_lam0 = std::sqrt(lam0);
758 const double sqrt_r = std::sqrt(r);
759 double s = sqrt_lam0;
760 for (
int n = 0; n < N_; ++n) {
766 const Eigen::MatrixXd Phi = eigenfunctions(
x);
767 Eigen::MatrixXd A = Phi;
768 A.array().rowwise() *= sqrt_lam_.transpose().array();
773 Eigen::BDCSVD<Eigen::MatrixXd> svd(
774 A, Eigen::ComputeThinU | Eigen::ComputeThinV);
775 const Eigen::VectorXd& S = svd.singularValues();
776 const double thresh = sv_rtol * S(0);
778 while (rank_ < S.size() && S(rank_) > thresh)
781 const Eigen::MatrixXd Vr = svd.matrixV().leftCols(rank_);
782 const Eigen::VectorXd Sr = S.head(rank_);
783 W_ = Vr.array().rowwise() / Sr.transpose().array();
801 return Psi_X_.colPivHouseholderQr().solve(
y);
806 Eigen::MatrixXd A = eigenfunctions(xstar);
807 A.array().rowwise() *= sqrt_lam_.transpose().array();
812 const Eigen::VectorXd& b)
const
819 if (Psi_X_.size() == 0)
return 0.0;
820 Eigen::BDCSVD<Eigen::MatrixXd> svd(Psi_X_);
821 const Eigen::VectorXd& S = svd.singularValues();
822 if (S.size() == 0 || S(S.size() - 1) == 0.0)
return 0.0;
823 return S(0) / S(S.size() - 1);
834Eigen::MatrixXi gradedMultiIndices(
int dim,
int max_degree)
836 std::vector<std::vector<int>> idx;
837 std::vector<int> a(dim, 0);
841 for (
int k = 0; k < dim; ++k)
843 if (s <= max_degree) idx.push_back(a);
846 if (++a[k] <= max_degree)
break;
852 std::sort(idx.begin(), idx.end(),
853 [](
const std::vector<int>& p,
const std::vector<int>& q) {
859 if (sp != sq) return sp < sq;
862 Eigen::MatrixXi M(
static_cast<Eigen::Index
>(idx.size()), dim);
863 for (Eigen::Index i = 0; i < M.rows(); ++i)
864 for (
int k = 0; k < dim; ++k)
878 const int n =
static_cast<int>(coeffs.size());
879 if (tol >= 1.0)
return 1;
880 if (n < 17)
return n;
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];
891 int plateauPoint = 0, j2 = 0;
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;
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;
904 if (!found)
return n;
906 if (env[plateauPoint] == 0.0)
return std::max(plateauPoint, 1);
907 const double t76 = std::pow(tol, 7.0 / 6.0);
909 for (
int j = 1; j <= n; ++j)
910 if (env[j] >= t76) ++j3;
913 if (j2 <= n) env[j2] = t76;
915 const double slope = (-1.0 / 3.0) * std::log10(tol);
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)
922 const double cc = std::log10(env[j]) + lin;
928 return std::max(dmin - 1, 1);
932 int dim,
double target_tol,
int max_degree_cap)
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));
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));
955 if (deg < 1) deg = 1;
956 if (deg > max_degree_cap) deg = max_degree_cap;
963 if (dim < 0 || max_degree < 0 || limit < 0)
return true;
964 if (dim == 0 || max_degree == 0)
return 1 > limit;
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;
979 Eigen::Index mode_limit)
981 if (requested_degree <= 0)
return 0;
982 if (mode_limit <= 0)
return 0;
983 int degree = requested_degree;
990std::atomic<std::size_t> g_stable_basis_factorizations{0};
994 return g_stable_basis_factorizations.load(std::memory_order_relaxed);
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;
1024 double sv_rtol,
double sv_abs_tol,
1027 bordered_kernel_.resize(0, 0);
1028 bordered_assembly_error_ = 0.0;
1029 clearBorderedCache();
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;
1039 M_ =
static_cast<int>(kernel.rows());
1041 gradient_enhanced_ =
true;
1042 affine_full_dim_ = 0;
1044 sqrt_lam_.resize(0);
1046 A_train_.resize(0, 0);
1047 noisy_eigvals_.resize(0);
1049 if (kernel.rows() == 0 || kernel.rows() != kernel.cols()) {
1051 Psi_.resize(kernel.rows(), 0);
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) {
1062 Psi_.resize(kernel.rows(), 0);
1067 Eigen::VectorXd evals_asc = es.eigenvalues();
1068 Eigen::MatrixXd evecs_asc = es.eigenvectors();
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)));
1077 rank_ =
static_cast<int>(keptSingularRankWithChop(
1078 S, dualKernelSingularCutoff(S, sv_rtol, sv_abs_tol), sv_chop_tol,
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);
1087 bordered_kernel_ = std::move(sym);
1088 condition_number_ = rank_ > 0 ? 1.0 : 0.0;
1091#ifdef GPR_LINALG_SCALAPACK
1092bool StableBasisND::factorizeKernelDistributed(
const Eigen::MatrixXd& kernel,
1097 bordered_kernel_.resize(0, 0);
1098 bordered_assembly_error_ = 0.0;
1099 clearBorderedCache();
1103 lapack_rrr_value_range_used_ =
false;
1104 last_kernel_factorize_driver_ =
"serial_floor";
1105 condition_number_ = 0.0;
1107 M_ =
static_cast<int>(kernel.rows());
1109 gradient_enhanced_ =
true;
1110 affine_full_dim_ = 0;
1112 sqrt_lam_.resize(0);
1114 A_train_.resize(0, 0);
1115 noisy_eigvals_.resize(0);
1117 if (kernel.rows() == 0 || kernel.rows() != kernel.cols()) {
1119 Psi_.resize(kernel.rows(), 0);
1121 return kernel.rows() == kernel.cols();
1124 Eigen::MatrixXd sym = 0.5 * (kernel + kernel.transpose());
1125 bordered_assembly_error_ = kernelAssemblyErrorBound(kernel, sym);
1126 Eigen::MatrixXd evecs_asc;
1127 Eigen::VectorXd evals_asc;
1129 static_cast<Eigen::Index
>(std::numeric_limits<int>::max())) {
1131 Psi_.resize(kernel.rows(), 0);
1135 auto& st = backend().distributed();
1137 int eigensystem_ok = 0;
1138 const char* full_driver =
"serial_floor";
1139 last_kernel_factorize_driver_ = full_driver;
1140 if (dispatchAllEigenpairs(backend(), sym, evals_asc, evecs_asc,
1143 last_kernel_factorize_driver_ = full_driver;
1145 if (eigensystem_ok == 0) {
1148 fastAllEigenpairs(backend().mpi(), sym, evals_asc, evecs_asc)
1151 if (eigensystem_ok == 0) {
1152 Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> es =
1153 timedSymmetricEigen(sym);
1154 if (es.info() == Eigen::Success &&
1155 es.eigenvalues().size() > 0) {
1156 evals_asc = es.eigenvalues();
1157 evecs_asc = es.eigenvectors();
1163 MPI_Bcast(&eigensystem_ok, 1, MPI_INT, 0, st.world_comm());
1164 const int n_int =
static_cast<int>(kernel.rows());
1165 if (eigensystem_ok != 0) {
1166 if (!st.is_root()) {
1167 evals_asc.resize(n_int);
1168 evecs_asc.resize(n_int, n_int);
1170 MPI_Bcast(evals_asc.data(), n_int, MPI_DOUBLE, 0, st.world_comm());
1171 MPI_Bcast(evecs_asc.data(), n_int * n_int, MPI_DOUBLE, 0,
1175 if (eigensystem_ok == 0 || evals_asc.size() == 0 ||
1176 evecs_asc.rows() != kernel.rows()) {
1178 Psi_.resize(kernel.rows(), 0);
1183 const Eigen::Index n = evals_asc.size();
1184 Eigen::VectorXd S(n);
1185 for (Eigen::Index i = 0; i < n; ++i) {
1186 const Eigen::Index src = n - 1 - i;
1187 S(i) = std::sqrt(std::max(0.0, evals_asc(src)));
1190 rank_ =
static_cast<int>(keptSingularRankWithChop(
1191 S, dualKernelSingularCutoff(S, sv_rtol, sv_abs_tol), sv_chop_tol,
1194 Sr_ = S.head(rank_);
1195 Psi_.resize(kernel.rows(), rank_);
1196 for (Eigen::Index i = 0; i < rank_; ++i) {
1197 const Eigen::Index src = n - 1 - i;
1198 Psi_.col(i) = evecs_asc.col(src);
1200 bordered_kernel_ = std::move(sym);
1201 condition_number_ = rank_ > 0 ? 1.0 : 0.0;
1207 double sv_rtol,
double sv_abs_tol,
1209 bool allow_value_range)
1211 bordered_kernel_.resize(0, 0);
1212 bordered_assembly_error_ = 0.0;
1213 clearBorderedCache();
1217 lapack_rrr_value_range_used_ =
false;
1218 last_kernel_factorize_driver_ =
"unset";
1219 condition_number_ = 0.0;
1221 M_ =
static_cast<int>(kernel.rows());
1223 gradient_enhanced_ =
true;
1224 affine_full_dim_ = 0;
1226 sqrt_lam_.resize(0);
1228 A_train_.resize(0, 0);
1229 noisy_eigvals_.resize(0);
1231 if (kernel.rows() == 0 || kernel.rows() != kernel.cols()) {
1233 Psi_.resize(kernel.rows(), 0);
1235 return kernel.rows() == kernel.cols();
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_ &&
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";
1262 bool used_value_range =
false;
1269 if (!used_cached_spectrum && allow_value_range && sv_chop_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;
1281 if (!used_cached_spectrum && !used_value_range &&
1282 !fastAllEigenpairs(backend().mpi(), sym, evals_asc, evecs_asc,
1283 &last_kernel_factorize_driver_)) {
1285 Psi_.resize(kernel.rows(), 0);
1289 if (evals_asc.size() == 0) {
1291 Psi_.resize(kernel.rows(), 0);
1293 lapack_rrr_value_range_used_ = used_value_range;
1296 if (!used_cached_spectrum && !used_value_range) ++lapack_rrr_full_solves_;
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());
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)));
1313 rank_ =
static_cast<int>(keptSingularRankWithChop(
1314 S, dualKernelSingularCutoff(S, sv_rtol, sv_abs_tol), sv_chop_tol,
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);
1323 bordered_kernel_ = std::move(sym);
1324 lapack_rrr_value_range_used_ = used_value_range;
1325 condition_number_ = rank_ > 0 ? 1.0 : 0.0;
1337void finalizeNoisyKernel(
const Eigen::VectorXd& evals_asc,
1338 const Eigen::MatrixXd& evecs_asc,
double sigma2,
1339 int& rank_out, Eigen::MatrixXd& Psi_out,
1340 Eigen::VectorXd& Sr_out, Eigen::VectorXd& mu_out,
1341 double& condition_number_out)
1343 const Eigen::Index n = evals_asc.size();
1344 Psi_out.resize(evecs_asc.rows(), n);
1347 for (Eigen::Index i = 0; i < n; ++i) {
1348 const Eigen::Index src = n - 1 - i;
1349 const double mu = std::max(sigma2, evals_asc(src));
1351 Sr_out(i) = std::sqrt(std::max(0.0, mu - sigma2));
1352 Psi_out.col(i) = evecs_asc.col(src);
1354 rank_out =
static_cast<int>(n);
1355 condition_number_out = n > 0 ? 1.0 : 0.0;
1363 bordered_kernel_.resize(0, 0);
1364 bordered_assembly_error_ = 0.0;
1365 clearBorderedCache();
1369 lapack_rrr_value_range_used_ =
false;
1370 condition_number_ = 0.0;
1372 M_ =
static_cast<int>(noisy_kernel.rows());
1374 gradient_enhanced_ =
true;
1375 affine_full_dim_ = 0;
1377 sqrt_lam_.resize(0);
1379 A_train_.resize(0, 0);
1380 noisy_eigvals_.resize(0);
1382 if (noisy_kernel.rows() == 0 ||
1383 noisy_kernel.rows() != noisy_kernel.cols()) {
1385 Psi_.resize(noisy_kernel.rows(), 0);
1390 const Eigen::MatrixXd sym = 0.5 * (noisy_kernel + noisy_kernel.transpose());
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_);
1404 Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> es =
1405 timedSymmetricEigen(sym);
1406 if (es.info() != Eigen::Success || es.eigenvalues().size() == 0) {
1408 Psi_.resize(noisy_kernel.rows(), 0);
1412 finalizeNoisyKernel(es.eigenvalues(), es.eigenvectors(), sigma2, rank_,
1413 Psi_, Sr_, noisy_eigvals_, condition_number_);
1417 const Eigen::MatrixXd& noisy_kernel,
double sigma2)
1419 bordered_kernel_.resize(0, 0);
1420 bordered_assembly_error_ = 0.0;
1421 clearBorderedCache();
1425 lapack_rrr_value_range_used_ =
false;
1426 condition_number_ = 0.0;
1428 M_ =
static_cast<int>(noisy_kernel.rows());
1430 gradient_enhanced_ =
true;
1431 affine_full_dim_ = 0;
1433 sqrt_lam_.resize(0);
1435 A_train_.resize(0, 0);
1436 noisy_eigvals_.resize(0);
1438 if (noisy_kernel.rows() == 0 ||
1439 noisy_kernel.rows() != noisy_kernel.cols()) {
1441 Psi_.resize(noisy_kernel.rows(), 0);
1443 return noisy_kernel.rows() == noisy_kernel.cols();
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)) {
1451 Psi_.resize(noisy_kernel.rows(), 0);
1455 if (evals_asc.size() == 0) {
1457 Psi_.resize(noisy_kernel.rows(), 0);
1461 finalizeNoisyKernel(evals_asc, evecs_asc, sigma2, rank_, Psi_, Sr_,
1462 noisy_eigvals_, condition_number_);
1467 int sketch_size,
int n_power_iter,
1468 double sv_rtol,
double sv_abs_tol,
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) {
1482 M_ =
static_cast<int>(kernel.rows());
1484 gradient_enhanced_ =
true;
1485 affine_full_dim_ = 0;
1487 sqrt_lam_.resize(0);
1489 A_train_.resize(0, 0);
1491 if (kernel.rows() == 0 || kernel.rows() != kernel.cols()) {
1493 Psi_.resize(kernel.rows(), 0);
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);
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);
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);
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();
1526 Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> es =
1527 timedSymmetricEigen(T);
1528 if (es.info() != Eigen::Success || es.eigenvalues().size() == 0) {
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);
1545 const Eigen::Index rk = keptSingularRankWithChop(
1546 S, dualKernelSingularCutoff(S, sv_rtol, sv_abs_tol), sv_chop_tol,
1548 if (rk == l && l < n) {
1549 l = std::min<Eigen::Index>(2 * l, n);
1553 rank_ =
static_cast<int>(rk);
1557 Psi_ = Q * Z.leftCols(rk);
1558 bordered_kernel_ = std::move(sym);
1559 condition_number_ = rank_ > 0 ? 1.0 : 0.0;
1565 Eigen::Index full_rows, Eigen::MatrixXd lifted_psi,
1566 const detail::RigidDeflationState& deflation,
double extra_assembly_error)
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;
1580 bordered_deflation_ =
1581 std::make_shared<detail::RigidDeflationState>(deflation);
1583 bordered_kernel_.resize(0, 0);
1584 bordered_assembly_error_ = 0.0;
1589 const Eigen::MatrixXd& cross_old_new,
1590 const Eigen::MatrixXd& new_kernel,
1591 double sv_rtol,
double sv_abs_tol,
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;
1604 M_ =
static_cast<int>(old_basis.
numObs() + new_kernel.rows());
1606 gradient_enhanced_ =
true;
1607 affine_full_dim_ = 0;
1608 overall_scale_ = 1.0;
1613 sqrt_lam_.resize(0);
1615 A_train_.resize(0, 0);
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 ||
1626 Psi_.resize(std::max<Eigen::Index>(0, n_old + n_new), 0);
1633 const Eigen::MatrixXd C = cross_old_new;
1634 const Eigen::MatrixXd D = 0.5 * (new_kernel + new_kernel.transpose());
1636 Eigen::MatrixXd UtC;
1640 UtC.noalias() = U.transpose() * C;
1641 const Eigen::MatrixXd residual = C - U * UtC;
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())) *
1655 while (q_rank < Rsv.size() && Rsv(q_rank) > tol)
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);
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();
1674 Eigen::MatrixXd QtC;
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();
1682 projected.bottomRightCorner(n_new, n_new) = D;
1683 projected = 0.5 * (projected + projected.transpose()).eval();
1685 Eigen::VectorXd evals_asc;
1686 Eigen::MatrixXd evecs_asc;
1707 const char* append_driver =
"serial_floor";
1708 if (dispatchAllEigenpairs(backend(), projected, evals_asc, evecs_asc,
1710 last_kernel_factorize_driver_ = append_driver;
1711 }
else if (fastAllEigenpairs(backend().mpi(), projected, evals_asc,
1713 fast_kernel_eigensolver_used_ =
true;
1715 Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> es =
1716 timedSymmetricEigen(projected);
1717 if (es.info() != Eigen::Success || es.eigenvalues().size() == 0) {
1719 Psi_.resize(n_old + n_new, 0);
1723 evals_asc = es.eigenvalues();
1724 evecs_asc = es.eigenvectors();
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);
1735 rank_ =
static_cast<int>(keptSingularRankWithChop(
1736 Snew, dualKernelSingularCutoff(Snew, sv_rtol, sv_abs_tol), sv_chop_tol,
1739 Sr_ = Snew.head(rank_);
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();
1748 const Eigen::MatrixXd Zr = Z.leftCols(rank_);
1749 bool multiplied =
false;
1750#ifdef GPR_LINALG_SCALAPACK
1751 auto& state = backend().distributed();
1753 if (!reproducibleBasis() && state.nprocs() > 1 &&
1754 std::min({P.rows(), P.cols(), Zr.cols()}) >=
1756 multiplied = backend().distributed_gemm_nn(P, Zr, Psi_);
1760 Psi_.resize(P.rows(), Zr.cols());
1762 auto* gpu = availableGpuEigensolver(backend().mpi());
1763 if (!(gpu !=
nullptr && gpu->gemmNN(P, Zr, Psi_))) {
1764 Psi_.noalias() = P * Zr;
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;
1778 condition_number_ = rank_ > 0 ? 1.0 : 0.0;
1783 const Eigen::VectorXi& source_for_target)
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());
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;
1800 Psi_next.row(target) = Psi_.row(src);
1801 if (permute_design) A_next.row(target) = A_train_.row(src);
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));
1814 bordered_kernel_ = std::move(K_next);
1816 bordered_kernel_.resize(0, 0);
1817 bordered_assembly_error_ = 0.0;
1819 clearBorderedCache();
1824 const Eigen::MatrixXd& centered_X)
1826 const Eigen::Index d = centered_X.cols();
1827 if (centered_X.rows() == 0 || d == 0)
return Eigen::MatrixXd(d, 0);
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);
1833 const double tol = std::numeric_limits<double>::epsilon() *
1834 static_cast<double>(std::max(centered_X.rows(), d)) *
1836 Eigen::Index
rank = 0;
1837 while (
rank < S.size() && S(
rank) > tol)
1839 return svd.matrixV().leftCols(
rank);
1843 const Eigen::MatrixXd& basis,
1844 Eigen::MatrixXd& coords,
1845 Eigen::MatrixXd& residuals)
1847 coords = centered_X * basis;
1848 residuals = centered_X - coords * basis.transpose();
1851void StableBasisND::eigen1d(
double xk,
int dim, Eigen::VectorXd& val,
1852 Eigen::VectorXd& deriv)
const
1854 Eigen::VectorXd second;
1855 eigen1dSecond(xk, dim, val, deriv, second);
1858void StableBasisND::eigen1dSecond(
double xk,
int dim, Eigen::VectorXd& val,
1859 Eigen::VectorXd& deriv,
1860 Eigen::VectorXd& second)
const
1869 const int P = max_degree_;
1870 const double beta = beta_(dim);
1871 const double delta2 = delta2_(dim);
1872 const double u = alpha_ * beta * xk;
1873 const double env = std::exp(-delta2 * xk * xk);
1875 deriv.resize(P + 1);
1876 second.resize(P + 1);
1877 Eigen::VectorXd psi(P + 1);
1878 psi(0) = std::sqrt(beta);
1879 if (P >= 1) psi(1) = std::sqrt(2.0) * std::sqrt(beta) * u;
1880 for (
int n = 1; n < P; ++n)
1881 psi(n + 1) = std::sqrt(2.0 / (n + 1)) * u * psi(n) -
1882 std::sqrt(
static_cast<double>(n) / (n + 1)) * psi(n - 1);
1883 for (
int n = 0; n <= P; ++n) {
1884 val(n) = env * psi(n);
1886 (n > 0) ? alpha_ * beta * std::sqrt(2.0 * n) * psi(n - 1) : 0.0;
1887 const double ddpsi =
1889 ? alpha_ * alpha_ * beta * beta * 2.0 *
1890 std::sqrt(
static_cast<double>(n) * (n - 1)) * psi(n - 2)
1892 deriv(n) = env * (dpsi - 2.0 * delta2 * xk * psi(n));
1894 env * (ddpsi - 4.0 * delta2 * xk * dpsi +
1895 (4.0 * delta2 * delta2 * xk * xk - 2.0 * delta2) * psi(n));
1899void StableBasisND::eigen1dEpsDerivative(
double xk,
int dim,
1900 Eigen::VectorXd& val,
1901 Eigen::VectorXd& dval_eps)
const
1907 const int P = max_degree_;
1908 const double beta = beta_(dim);
1909 const double delta2 = delta2_(dim);
1910 const double eps = eps_(dim);
1911 const double u = alpha_ * beta * xk;
1912 const double env = std::exp(-delta2 * xk * xk);
1913 const double dbeta = 2.0 * eps / (alpha_ * alpha_ * beta * beta * beta);
1914 const double ddelta2 = alpha_ * alpha_ * beta * dbeta;
1915 const double du = alpha_ * dbeta * xk;
1916 const double denv = env * (-(xk * xk) * ddelta2);
1917 const double sb = std::sqrt(beta);
1918 const double dsb = dbeta / (2.0 * sb);
1920 dval_eps.resize(P + 1);
1921 Eigen::VectorXd psi(P + 1), dpsi(P + 1);
1925 psi(1) = std::sqrt(2.0) * sb * u;
1926 dpsi(1) = std::sqrt(2.0) * (dsb * u + sb * du);
1928 for (
int n = 1; n < P; ++n) {
1929 const double a = std::sqrt(2.0 / (n + 1));
1930 const double b = std::sqrt(
static_cast<double>(n) / (n + 1));
1931 psi(n + 1) = a * u * psi(n) - b * psi(n - 1);
1932 dpsi(n + 1) = a * (du * psi(n) + u * dpsi(n)) - b * dpsi(n - 1);
1934 for (
int n = 0; n <= P; ++n) {
1935 val(n) = env * psi(n);
1936 dval_eps(n) = denv * psi(n) + env * dpsi(n);
1940void StableBasisND::eigenTensor(
const Eigen::MatrixXd& X,
bool want_grad,
1941 Eigen::MatrixXd& Phi,
1942 std::vector<Eigen::MatrixXd>& dPhi)
const
1944 const Eigen::Index m = X.rows();
1945 const Eigen::Index N = midx_.rows();
1947 std::vector<std::vector<Eigen::VectorXd>> V(m), D(m);
1948 for (Eigen::Index i = 0; i < m; ++i) {
1951 for (
int k = 0; k < dim_; ++k)
1952 eigen1d(X(i, k), k, V[i][k], D[i][k]);
1955 for (Eigen::Index c = 0; c < N; ++c)
1956 for (Eigen::Index i = 0; i < m; ++i) {
1958 for (
int k = 0; k < dim_; ++k)
1959 p *= V[i][k](midx_(c, k));
1962 if (!want_grad)
return;
1963 dPhi.assign(dim_, Eigen::MatrixXd::Zero(m, N));
1964 for (
int j = 0; j < dim_; ++j)
1965 for (Eigen::Index c = 0; c < N; ++c)
1966 for (Eigen::Index i = 0; i < m; ++i) {
1968 for (
int k = 0; k < dim_; ++k)
1969 p *= (k == j) ? D[i][k](midx_(c, k)) : V[i][k](midx_(c, k));
1975 Eigen::MatrixXd& Phi,
1976 Eigen::MatrixXd& dPhi_eps)
const
1978 const Eigen::Index m = X.rows();
1979 const Eigen::Index N = midx_.rows();
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) {
1985 for (
int k = 0; k < dim_; ++k) {
1987 eigen1dEpsDerivative(X(i, k), k, V[i][k], dVj[i]);
1990 eigen1d(X(i, k), k, V[i][k], d);
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;
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));
2004 dPhi_eps(i, c) = dp;
2008void StableBasisND::buildSqrtLamAndPrune(
const Eigen::VectorXd& r,
2009 const Eigen::VectorXd& lam0,
2010 double scl,
double prune_rtol)
2012 const Eigen::Index Nfull = midx_.rows();
2013 Eigen::VectorXd lamfull(Nfull);
2014 for (Eigen::Index c = 0; c < Nfull; ++c) {
2016 for (
int k = 0; k < dim_; ++k)
2017 s *= std::sqrt(lam0(k)) * std::pow(std::sqrt(r(k)), midx_(c, k));
2018 lamfull(c) = scl * s;
2020 if (prune_rtol <= 0.0 || Nfull == 0) {
2021 sqrt_lam_ = std::move(lamfull);
2029 const double thresh = prune_rtol * lamfull.maxCoeff();
2030 std::vector<Eigen::Index> keep;
2031 keep.reserve(
static_cast<size_t>(Nfull));
2032 for (Eigen::Index c = 0; c < Nfull; ++c)
2033 if (lamfull(c) >= thresh) keep.push_back(c);
2034 const Eigen::Index Nk =
static_cast<Eigen::Index
>(keep.size());
2035 Eigen::MatrixXi midx_keep(Nk, dim_);
2036 Eigen::VectorXd lam_keep(Nk);
2037 for (Eigen::Index j = 0; j < Nk; ++j) {
2038 midx_keep.row(j) = midx_.row(keep[
static_cast<size_t>(j)]);
2039 lam_keep(j) = lamfull(keep[
static_cast<size_t>(j)]);
2041 midx_ = std::move(midx_keep);
2042 sqrt_lam_ = std::move(lam_keep);
2045void StableBasisND::eigenTensorCols(
const Eigen::MatrixXd& X,
bool want_grad,
2046 Eigen::Index c0, Eigen::Index count,
2047 Eigen::MatrixXd& Phi,
2048 std::vector<Eigen::MatrixXd>& dPhi)
const
2050 const Eigen::Index m = X.rows();
2052 std::vector<std::vector<Eigen::VectorXd>> V(m), D(m);
2053 for (Eigen::Index i = 0; i < m; ++i) {
2056 for (
int k = 0; k < dim_; ++k)
2057 eigen1d(X(i, k), k, V[i][k], D[i][k]);
2059 Phi.setOnes(m, count);
2060 for (Eigen::Index cc = 0; cc < count; ++cc) {
2061 const Eigen::Index c = c0 + cc;
2062 for (Eigen::Index i = 0; i < m; ++i) {
2064 for (
int k = 0; k < dim_; ++k)
2065 p *= V[i][k](midx_(c, k));
2069 if (!want_grad)
return;
2070 dPhi.assign(dim_, Eigen::MatrixXd::Zero(m, count));
2071 for (
int j = 0; j < dim_; ++j)
2072 for (Eigen::Index cc = 0; cc < count; ++cc) {
2073 const Eigen::Index c = c0 + cc;
2074 for (Eigen::Index i = 0; i < m; ++i) {
2076 for (
int k = 0; k < dim_; ++k)
2077 p *= (k == j) ? D[i][k](midx_(c, k)) : V[i][k](midx_(c, k));
2084 const Eigen::VectorXd& eps,
double alpha,
2085 int max_degree,
bool gradient_enhanced,
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());
2096 max_degree_ = max_degree;
2097 gradient_enhanced_ = gradient_enhanced;
2098 affine_full_dim_ = 0;
2099 overall_scale_ = 1.0;
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);
2113 midx_ = gradedMultiIndices(dim_, max_degree);
2114 const Eigen::Index N = midx_.rows();
2116 sqrt_lam_.resize(N);
2117 for (Eigen::Index c = 0; c < N; ++c) {
2119 for (
int k = 0; k < dim_; ++k)
2120 s *= std::sqrt(lam0(k)) * std::pow(std::sqrt(r(k)), midx_(c, k));
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();
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);
2143 while (rank_ < S.size() && S(rank_) > thresh)
2146 const Eigen::MatrixXd Vr = svd.matrixV().leftCols(rank_);
2147 Sr_ = S.head(rank_);
2148 W_ = Vr.array().rowwise() / Sr_.transpose().array();
2156 Psi_ = svd.matrixU().leftCols(rank_);
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;
2178 condition_number_ = rank_ > 0 ? 1.0 : 0.0;
2182 const Eigen::MatrixXd& X,
const Eigen::VectorXd& eps,
double alpha,
2183 double overall_scale,
int max_degree,
2184 const std::vector<Eigen::MatrixXd>& jacobians,
bool component_major,
2185 double sv_rtol,
int sketch_size,
int n_power_iter,
double mode_prune_rtol,
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());
2197 max_degree_ = max_degree;
2198 gradient_enhanced_ =
true;
2199 affine_full_dim_ = 0;
2200 overall_scale_ = overall_scale;
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);
2213 midx_ = gradedMultiIndices(dim_, max_degree);
2216 const double scl = std::sqrt(overall_scale);
2217 buildSqrtLamAndPrune(r, lam0, scl, mode_prune_rtol);
2218 const Eigen::Index N = midx_.rows();
2221 Eigen::MatrixXd Phi;
2222 std::vector<Eigen::MatrixXd> dPhi;
2223 eigenTensor(X,
true, Phi, dPhi);
2225 Eigen::Index ngrad = 0;
2226 for (
const auto& J: jacobians)
2228 const Eigen::Index nobs =
static_cast<Eigen::Index
>(M_) + ngrad;
2229 Eigen::MatrixXd A(nobs, N);
2230 A.topRows(M_) = Phi;
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);
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);
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);
2258 A.array().rowwise() *= sqrt_lam_.transpose().array();
2260 if (sketch_size > 0 && sketch_size < nobs) {
2261 factorizeFromDesignRandomized(A, sketch_size, n_power_iter, sv_rtol,
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();
2282 Psi_ = svd.matrixU().leftCols(rank_);
2284 condition_number_ = rank_ > 0 ? 1.0 : 0.0;
2288 const Eigen::MatrixXd& U,
const Eigen::VectorXd& eps,
double alpha,
2289 double overall_scale,
int max_degree,
2290 const std::vector<Eigen::MatrixXd>& jac_tangent,
2291 const std::vector<Eigen::MatrixXd>& jac_normal,
bool component_major,
2292 double sv_rtol,
int sketch_size,
int n_power_iter,
double mode_prune_rtol,
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());
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;
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);
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_);
2326 Eigen::MatrixXd Phi;
2327 std::vector<Eigen::MatrixXd> dPhi;
2328 eigenTensor(U,
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();
2335 Eigen::Index ngrad = 0;
2336 for (
const auto& J: jac_tangent)
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;
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);
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);
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);
2366 if (sketch_size > 0 && sketch_size < nobs) {
2367 factorizeFromDesignRandomized(A, sketch_size, n_power_iter, sv_rtol,
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_);
2383 condition_number_ = rank_ > 0 ? 1.0 : 0.0;
2386#ifdef GPR_LINALG_SCALAPACK
2387bool StableBasisND::factorizeGPCartesianDistributed(
2388 const Eigen::MatrixXd& X,
const Eigen::VectorXd& eps,
double alpha,
2389 double overall_scale,
int max_degree,
2390 const std::vector<Eigen::MatrixXd>& jacobians,
bool component_major,
2391 double sv_rtol,
double mode_prune_rtol)
2393 validateJointJacobians(X, jacobians);
2394 bordered_kernel_.resize(0, 0);
2395 bordered_assembly_error_ = 0.0;
2396 clearBorderedCache();
2397 lapack_rrr_value_range_used_ =
false;
2398 condition_number_ = 0.0;
2401 dim_ =
static_cast<int>(X.cols());
2402 M_ =
static_cast<int>(X.rows());
2404 max_degree_ = max_degree;
2405 gradient_enhanced_ =
true;
2408 delta2_.resize(dim_);
2409 Eigen::VectorXd r(dim_), lam0(dim_);
2410 for (
int k = 0; k < dim_; ++k) {
2411 const double e = eps_(k);
2412 beta_(k) = std::pow(1.0 + std::pow(2.0 * e / alpha, 2), 0.25);
2413 delta2_(k) = alpha * alpha / 2.0 * (beta_(k) * beta_(k) - 1.0);
2414 const double denom = alpha * alpha + delta2_(k) + e * e;
2415 r(k) = e * e / denom;
2416 lam0(k) = std::sqrt(alpha * alpha / denom);
2418 midx_ = gradedMultiIndices(dim_, max_degree);
2419 const double scl = std::sqrt(overall_scale);
2420 buildSqrtLamAndPrune(r, lam0, scl, mode_prune_rtol);
2421 const Eigen::Index N = midx_.rows();
2424 auto& st = backend().distributed();
2426 int c0i = 0, cnt = 0;
2427 st.col_block_range(
static_cast<int>(N), c0i, cnt);
2428 const Eigen::Index c0 = c0i;
2429 const Eigen::Index count = cnt;
2432 Eigen::MatrixXd Phi;
2433 std::vector<Eigen::MatrixXd> dPhi;
2434 eigenTensorCols(X,
true, c0, count, Phi, dPhi);
2436 Eigen::Index ngrad = 0;
2437 for (
const auto& J: jacobians)
2439 const Eigen::Index nobs =
static_cast<Eigen::Index
>(M_) + ngrad;
2440 Eigen::MatrixXd Aloc(nobs, count);
2442 Aloc.topRows(M_) = Phi;
2445 auto force_row = [&](
int i, Eigen::Index comp) {
2446 Eigen::RowVectorXd g = Eigen::RowVectorXd::Zero(count);
2447 for (
int k = 0; k < dim_; ++k)
2448 g += jacobians[i](k, comp) * dPhi[k].row(i);
2451 Eigen::Index row = M_;
2452 if (component_major) {
2453 const Eigen::Index C = jacobians.empty() ? 0 : jacobians[0].cols();
2454 for (Eigen::Index comp = 0; comp < C; ++comp)
2455 for (
int i = 0; i < M_; ++i)
2456 Aloc.row(row++) = force_row(i, comp);
2458 for (
int i = 0; i < M_; ++i)
2459 for (Eigen::Index comp = 0; comp < jacobians[i].cols(); ++comp)
2460 Aloc.row(row++) = force_row(i, comp);
2462 Aloc.array().rowwise() *=
2463 sqrt_lam_.segment(c0, count).transpose().array();
2470 Eigen::MatrixXd U, V;
2473 static_cast<int>(N), U, S, V))
2476 const double thresh = sv_rtol * S(0);
2478 while (rank_ < S.size() && S(rank_) > thresh)
2481 const Eigen::MatrixXd Vr = V.leftCols(rank_);
2482 Sr_ = S.head(rank_);
2483 W_ = Vr.array().rowwise() / Sr_.transpose().array();
2484 Psi_ = U.leftCols(rank_);
2488 A_train_.resize(0, 0);
2489 condition_number_ = rank_ > 0 ? 1.0 : 0.0;
2501void StableBasisND::factorizeFromDesignRandomized(
const Eigen::MatrixXd& A,
2502 int sketch,
int n_power,
2506 bordered_kernel_.resize(0, 0);
2507 bordered_assembly_error_ = 0.0;
2508 clearBorderedCache();
2509 condition_number_ = 0.0;
2510 const Eigen::Index nobs = A.rows();
2511 const Eigen::Index N = A.cols();
2512 std::mt19937_64 gen(0xC0FFEEULL);
2513 std::normal_distribution<double> nd(0.0, 1.0);
2514 Eigen::Index l = std::min<Eigen::Index>(sketch, nobs);
2517 Eigen::MatrixXd Omega(N, l);
2518 for (Eigen::Index j = 0; j < l; ++j)
2519 for (Eigen::Index i = 0; i < N; ++i)
2520 Omega(i, j) = nd(gen);
2524 Eigen::MatrixXd Y = A * Omega;
2525 for (
int p = 0; p < n_power; ++p) {
2526 const Eigen::MatrixXd Q1 =
2527 Eigen::HouseholderQR<Eigen::MatrixXd>(Y).householderQ() *
2528 Eigen::MatrixXd::Identity(nobs, l);
2529 const Eigen::MatrixXd Z = A.transpose() * Q1;
2530 const Eigen::MatrixXd Q2 =
2531 Eigen::HouseholderQR<Eigen::MatrixXd>(Z).householderQ() *
2532 Eigen::MatrixXd::Identity(N, l);
2535 const Eigen::MatrixXd Q =
2536 Eigen::HouseholderQR<Eigen::MatrixXd>(Y).householderQ() *
2537 Eigen::MatrixXd::Identity(nobs, l);
2539 const Eigen::MatrixXd B = Q.transpose() * A;
2540 Eigen::BDCSVD<Eigen::MatrixXd> svdB(
2541 B, Eigen::ComputeThinU | Eigen::ComputeThinV);
2542 const Eigen::VectorXd& S = svdB.singularValues();
2543 const double thresh = singularCutoff(S, sv_rtol, sv_abs_tol);
2544 const Eigen::Index rk = keptSingularRank(S, thresh);
2549 if (rk == l && l < nobs) {
2550 l = std::min<Eigen::Index>(2 * l, nobs);
2554 rank_ =
static_cast<int>(rk);
2558 Psi_ = Q * svdB.matrixU().leftCols(rk);
2560 const Eigen::MatrixXd Vr = svdB.matrixV().leftCols(rk);
2561 W_ = Vr.array().rowwise() / Sr_.transpose().array();
2563 condition_number_ = rank_ > 0 ? 1.0 : 0.0;
2568void StableBasisND::designAt(
const Eigen::MatrixXd& Xstar, Eigen::MatrixXd& A_E,
2569 std::vector<Eigen::MatrixXd>& A_g)
const
2571 Eigen::MatrixXd Phi;
2572 std::vector<Eigen::MatrixXd> dPhi;
2573 eigenTensor(Xstar,
true, Phi, dPhi);
2574 A_E = Phi.array().rowwise() * sqrt_lam_.transpose().array();
2576 for (
int j = 0; j < dim_; ++j)
2577 A_g[j] = dPhi[j].array().rowwise() * sqrt_lam_.transpose().array();
2580void StableBasisND::designAtAffineEnergy(
const Eigen::MatrixXd& Ustar,
2581 const Eigen::MatrixXd& residuals,
2582 Eigen::MatrixXd& A_E,
2583 AffineVariancePrior* prior)
const
2585 Eigen::MatrixXd Phi;
2586 std::vector<Eigen::MatrixXd> dPhi;
2587 eigenTensor(Ustar,
false, Phi, dPhi);
2588 const Eigen::Index m = Ustar.rows();
2589 const Eigen::Index N = midx_.rows();
2590 Eigen::MatrixXd Phi_s =
2591 Phi.array().rowwise() * sqrt_lam_.transpose().array();
2596 prior->diagonal.resize(m);
2598 if (prior->stable) {
2599 for (Eigen::Index i = 0; i < m; ++i)
2600 prior->diagonal(i) = Phi_s.row(i).cast<Work>().squaredNorm();
2602 for (Eigen::Index i = 0; i < m; ++i)
2603 prior->diagonal(i) =
2604 static_cast<Work
>(Phi_s.row(i).squaredNorm());
2607 A_E = Eigen::MatrixXd::Zero(m, N * (1 + affine_full_dim_));
2608 const double sqrt2 = std::sqrt(2.0);
2609 for (Eigen::Index i = 0; i < m; ++i) {
2610 const double scale = std::exp(-residuals.row(i).squaredNorm());
2611 A_E.block(i, 0, 1, N) = scale * Phi_s.row(i);
2612 for (Eigen::Index p = 0; p < affine_full_dim_; ++p) {
2613 A_E.block(i, (p + 1) * N, 1, N) =
2614 scale * sqrt2 * residuals(i, p) * Phi_s.row(i);
2621 return Psi_.colPivHouseholderQr().solve(
y);
2625 const Eigen::VectorXd& b)
const
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;
2634 const Eigen::VectorXd& b)
const
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;
2646 const Eigen::MatrixXd& Ustar,
const Eigen::MatrixXd& residuals,
2647 const Eigen::VectorXd& b)
const
2649 Eigen::MatrixXd A_E;
2650 designAtAffineEnergy(Ustar, residuals, A_E);
2651 return (A_E * W_) * b;
2655 const Eigen::MatrixXd& Ustar,
const Eigen::MatrixXd& residuals)
const
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();
2664 const Eigen::MatrixXd& Ustar,
const Eigen::MatrixXd& residuals,
2665 const Eigen::MatrixXd& basis,
const Eigen::VectorXd& b)
const
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();
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_);
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));
2694 const double normal_dot = ri.dot(normal_values);
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;
2705 Eigen::RowVectorXd gr(affine_full_dim_);
2706 for (Eigen::Index p = 0; p < affine_full_dim_; ++p) {
2708 scale * (-2.0 * ri(p) * base_value +
2709 sqrt2 * (normal_values(p) - 2.0 * ri(p) * normal_dot));
2711 G.row(i) = gu * basis.transpose() + gr * projector;
2717 const Eigen::MatrixXd& Ustar,
const Eigen::MatrixXd& residuals,
2718 const Eigen::MatrixXd& basis,
const Eigen::MatrixXd& tangent_directions,
2719 const Eigen::MatrixXd& residual_directions,
const Eigen::VectorXd& b)
const
2721 const Eigen::Index m = Ustar.rows();
2722 const Eigen::Index N = midx_.rows();
2724 std::vector<std::vector<Eigen::VectorXd>> V(m), D(m), DD(m);
2725 for (Eigen::Index i = 0; i < m; ++i) {
2729 for (
int k = 0; k < dim_; ++k)
2730 eigen1dSecond(Ustar(i, k), k, V[i][k], D[i][k], DD[i][k]);
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));
2738 for (Eigen::Index c = 0; c < N; ++c) {
2739 for (Eigen::Index i = 0; i < m; ++i) {
2741 for (
int k = 0; k < dim_; ++k)
2742 p *= V[i][k](midx_(c, k));
2745 for (
int j = 0; j < dim_; ++j) {
2747 for (
int k = 0; k < dim_; ++k)
2749 (k == j) ? D[i][k](midx_(c, k)) : V[i][k](midx_(c, k));
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));
2761 term *= V[i][k](midx_(c, k));
2765 d2PhiDirection[j](i, c) = hp;
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();
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_);
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);
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);
2800 const double dbase_value = base_grad.dot(tangent_directions.row(i));
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);
2816 normal_grad.row(p).dot(tangent_directions.row(i));
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);
2824 (dri(p) * normal_grad.row(p) + ri(p) * normal_hv.row(p));
2826 const Eigen::RowVectorXd dgu = dscale * gu_arg + scale * dgu_arg;
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;
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);
2841 const Eigen::RowVectorXd dgr = dscale * gr_arg + scale * dgr_arg;
2842 HV.row(i) = dgu * basis.transpose() + dgr * projector;
2848 const Eigen::VectorXd&
y,
double sigma2)
const
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();
2878inline double spectralFloorSigma2(
const Eigen::VectorXd& Sr,
double sigma2,
2879 Eigen::Index nobs,
double resolution_factor)
2881 if (Sr.size() == 0)
return sigma2;
2882 if (!(resolution_factor > 0.0 && resolution_factor < 1.0))
return sigma2;
2892 const double s2_max = dir::mulUp(Sr(0), Sr(0));
2895 const double s2_min =
2896 Sr.size() < nobs ? 0.0
2897 : dir::mulDown(Sr(Sr.size() - 1), Sr(Sr.size() - 1));
2898 const double numerator =
2899 dir::subUp(dir::mulUp(resolution_factor, s2_max), s2_min);
2900 const double denominator = dir::subDown(1.0, resolution_factor);
2901 const double floor = dir::divUp(numerator, denominator);
2902 return (std::isfinite(floor) && floor > sigma2) ? floor : sigma2;
2905inline double conditionFlooredSigma2(
const Eigen::VectorXd& Sr,
double sigma2,
2908 const double neps =
static_cast<double>(std::max<Eigen::Index>(1, nobs)) *
2909 std::numeric_limits<double>::epsilon();
2910 return spectralFloorSigma2(Sr, sigma2, nobs, neps);
2919inline double varianceFlooredSigma2(
const Eigen::VectorXd& Sr,
double sigma2,
2923 return conditionFlooredSigma2(Sr, sigma2, nobs);
2924 return spectralFloorSigma2(Sr, sigma2, nobs,
2925 std::numeric_limits<double>::epsilon());
2928double nonnegativeEigenmodeVariance(
const Eigen::VectorXd& projected,
2929 const Eigen::VectorXd& residual,
2930 const Eigen::VectorXd& singular_values,
2931 double sigma2,
double complement_eigenvalue,
2934 const double prior_value = prior.value();
2936 Eigen::VectorXd retained_coordinates(singular_values.size());
2937 for (Eigen::Index mode = 0; mode < singular_values.size(); ++mode) {
2938 const double singular = singular_values(mode);
2939 if (!(singular > 0.0) || !std::isfinite(singular))
2940 return std::numeric_limits<double>::quiet_NaN();
2941 const double coordinate = projected(mode) / singular;
2942 retained_coordinates(mode) = coordinate;
2943 prior.addProduct(-coordinate, coordinate);
2946 Eigen::VectorXd complement_coordinates;
2947 if (use_complement) {
2948 if (!(complement_eigenvalue > 0.0) ||
2949 !std::isfinite(complement_eigenvalue))
2950 return std::numeric_limits<double>::quiet_NaN();
2951 complement_coordinates = residual / std::sqrt(complement_eigenvalue);
2952 for (Eigen::Index row = 0; row < complement_coordinates.size(); ++row)
2953 prior.addProduct(-complement_coordinates(row),
2954 complement_coordinates(row));
2957 double unresolved_tail = prior.value();
2963 const double tail_roundoff =
2964 std::numeric_limits<double>::epsilon() * std::abs(prior_value);
2965 if (unresolved_tail < 0.0) {
2966 if (std::abs(unresolved_tail) <= tail_roundoff)
2967 unresolved_tail = 0.0;
2976 for (Eigen::Index mode = 0; mode < singular_values.size(); ++mode) {
2977 const double s2 = singular_values(mode) * singular_values(mode);
2978 direct.addTripleProduct(-retained_coordinates(mode),
2979 retained_coordinates(mode),
2980 s2 / (s2 + sigma2));
2982 if (use_complement) {
2983 const double explained =
2984 complement_eigenvalue / (complement_eigenvalue + sigma2);
2985 for (Eigen::Index row = 0; row < complement_coordinates.size();
2987 direct.addTripleProduct(-complement_coordinates(row),
2988 complement_coordinates(row),
2991 double value = direct.
value();
2992 if (value < 0.0 && std::abs(value) <= tail_roundoff) value = 0.0;
2993 return value >= 0.0 ? value
2994 : std::numeric_limits<double>::quiet_NaN();
3000 for (Eigen::Index mode = 0; mode < singular_values.size(); ++mode) {
3001 const double s2 = singular_values(mode) * singular_values(mode);
3002 const double attenuation = sigma2 / (s2 + sigma2);
3003 variance.addTripleProduct(retained_coordinates(mode),
3004 retained_coordinates(mode), attenuation);
3006 if (use_complement) {
3007 const double attenuation = sigma2 / (complement_eigenvalue + sigma2);
3008 for (Eigen::Index row = 0; row < complement_coordinates.size(); ++row)
3009 variance.addTripleProduct(complement_coordinates(row),
3010 complement_coordinates(row), attenuation);
3018void projectOntoStableBasis(
const Eigen::MatrixXd& psi,
3019 const Eigen::MatrixXd& cross,
3020 Eigen::MatrixXd& projected,
3021 Eigen::MatrixXd& residual)
3023 projected = psi.transpose() * cross;
3024 residual = cross - psi * projected;
3025 const Eigen::MatrixXd correction = psi.transpose() * residual;
3026 residual.noalias() -= psi * correction;
3027 projected += correction;
3034 return conditionFlooredSigma2(Sr_, sigma2, Psi_.rows());
3039 return varianceFlooredSigma2(Sr_, sigma2, Psi_.rows());
3043 const Eigen::VectorXd& singular_values,
double sigma2, Eigen::Index nobs)
3045 return conditionFlooredSigma2(singular_values, sigma2, nobs);
3049 const Eigen::VectorXd&
y,
double sigma2)
const
3051 sigma2 = conditionFlooredSigma2(Sr_, sigma2, Psi_.rows());
3052 const Eigen::VectorXd
z = Psi_.transpose() *
y;
3057 const Eigen::ArrayXd mu =
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);
3067 const Eigen::VectorXd noisy_projected =
3068 Psi_ * (projected_inverse *
z.array()).matrix();
3070 weights.
alpha = noisy_projected;
3072 if (complement > 0.0) {
3073 weights.
alpha += complement * (
y - Psi_ *
z);
3075 weights.
reduced = (shrink *
z.array()).matrix();
3080 double sigma2)
const
3082 sigma2 = conditionFlooredSigma2(Sr_, sigma2, Psi_.rows());
3087 const Eigen::VectorXd p = Psi_.transpose() *
y;
3088 const Eigen::ArrayXd mu =
3090 : Eigen::ArrayXd(Sr_.array().square() + sigma2);
3091 const Eigen::ArrayXd d = mu.inverse();
3092 Eigen::VectorXd solved = Psi_ * (d.matrix().asDiagonal() * p);
3094 if (complement > 0.0) {
3095 solved += complement * (
y - Psi_ * p);
3101 double sigma2)
const
3103 if (rhs.rows() != Psi_.rows() || Psi_.cols() != Sr_.size() ||
3105 return Eigen::VectorXd();
3107 if (rhs.cols() == 0)
return Eigen::VectorXd();
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();
3126 const Eigen::MatrixXd& rhs,
double sigma2)
const
3132 sigma2 = conditionFlooredSigma2(Sr_, sigma2, Psi_.rows());
3133 if (rhs.rows() != Psi_.rows() || Psi_.cols() != Sr_.size() ||
3135 return Eigen::VectorXd();
3137 if (rhs.cols() == 0)
return Eigen::VectorXd();
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();
3150 const Eigen::MatrixXd& rhs,
const Eigen::VectorXd& prior,
3151 const Eigen::VectorXd& signal,
double sigma2,
bool check_variance)
const
3153 if (prior.size() != rhs.cols() || signal.size() != prior.size())
3155 "stable range posterior variance: prior, signal and query "
3156 "columns disagree");
3157 if (rhs.rows() != Psi_.rows() || Psi_.cols() != Sr_.size())
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))
3164 "stable range posterior variance: noise floor is not finite and "
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) {
3173 local_prior.
add(prior(column));
3174 variance(column) = nonnegativeEigenmodeVariance(
3175 projected.col(column), no_residual, Sr_, sigma2, 0.0,
3176 false, local_prior);
3187 Eigen::Matrix<Extended, Eigen::Dynamic, Eigen::Dynamic>;
3207 Eigen::Matrix<Extended, Eigen::Dynamic, Eigen::Dynamic>;
3216void StableBasisND::clearBorderedCache() noexcept
3218 bordered_deflation_.reset();
3219 std::lock_guard<std::mutex> lock(bordered_cache_.mutex);
3220 bordered_cache_.factor.reset();
3221 bordered_cache_.error.clear();
3222 bordered_cache_.rm.reset();
3225bool StableBasisND::extendedCertificationEnabledLocked()
const
3227 if (bordered_cache_.extended_override == 0)
return false;
3234 throw std::invalid_argument(
3235 "extended certification cannot be enabled on this platform");
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;
3244void StableBasisND::buildBorderedFactorLocked()
const
3246 if (!extendedCertificationEnabledLocked()) {
3247 throw BorderedVarianceError(
3248 "this platform cannot certify the bordered variance");
3251 using ExtendedMatrix =
3252 Eigen::Matrix<Extended, Eigen::Dynamic, Eigen::Dynamic>;
3253 using ExtendedVector = Eigen::Matrix<Extended, Eigen::Dynamic, 1>;
3255 if (!bordered_cache_.error.empty()) {
3256 throw BorderedVarianceError(bordered_cache_.error);
3259 if (!bordered_cache_.factor) {
3261 auto factor = std::make_shared<BorderedFactorCache>();
3264 if (bordered_kernel_.rows() == n && bordered_kernel_.cols() == n) {
3265 factor->is_kernel_path =
true;
3268 factor->Q.resize(0, 0);
3269 factor->R.resize(0, 0);
3271 if (!bordered_kernel_.allFinite()) {
3272 throw BorderedVarianceError(
3273 "the kernel matrix is not positive semidefinite");
3275 const ExtendedMatrix raw =
3276 bordered_kernel_.cast<Extended>();
3277 const ExtendedMatrix sym =
3278 Extended(0.5L) * (raw + raw.transpose());
3280 const Extended sym_residual = certifiedResidual(
3283 (raw.cwiseAbs() + raw.transpose().cwiseAbs()) +
3287 ExtendedVector diag_scale(n);
3288 ExtendedVector inv_scale(n);
3289 bool any_positive_diag =
false;
3290 Extended min_pos_d = 0.0L;
3291 Extended max_d = 0.0L;
3292 for (Eigen::Index i = 0; i < n; ++i) {
3293 const Extended v = sym(i, i);
3294 if (!(v >= Extended(0)) || !workingIsFinite(v)) {
3295 throw BorderedVarianceError(
3296 "the kernel matrix is not positive "
3300 any_positive_diag =
true;
3301 const Extended d = workingSqrt(v);
3303 inv_scale(i) = 1.0L / d;
3304 if (min_pos_d == 0.0L || d < min_pos_d)
3306 if (d > max_d) max_d = d;
3308 for (Eigen::Index j = 0; j < n; ++j) {
3309 if (sym(i, j) != 0.0L || sym(j, i) != 0.0L) {
3310 throw BorderedVarianceError(
3311 "the kernel matrix is not positive "
3315 diag_scale(i) = 0.0L;
3316 inv_scale(i) = 0.0L;
3320 if (!any_positive_diag) {
3322 factor->Q.resize(n, 0);
3323 factor->R.resize(0, 0);
3324 factor->eps_k = directedUpper(
3325 static_cast<Extended
>(bordered_assembly_error_) +
3328 factor->eps_k_ops = kAssemblyPairOps;
3330 ExtendedMatrix equilibrated = sym;
3331 for (Eigen::Index i = 0; i < n; ++i) {
3332 for (Eigen::Index j = 0; j < n; ++j) {
3333 equilibrated(i, j) *=
3334 inv_scale(i) * inv_scale(j);
3339 (equilibrated + equilibrated.transpose());
3340 ExtendedMatrix rescaled = equilibrated;
3341 for (Eigen::Index i = 0; i < n; ++i) {
3342 for (Eigen::Index j = 0; j < n; ++j) {
3343 rescaled(i, j) *= diag_scale(i) * diag_scale(j);
3348 ExtendedMatrix rescaled_abs = equilibrated.cwiseAbs();
3349 for (Eigen::Index i = 0; i < n; ++i) {
3350 for (Eigen::Index j = 0; j < n; ++j) {
3351 rescaled_abs(i, j) *=
3352 workingAbs(diag_scale(i) * diag_scale(j));
3355 const Extended scale_residual = certifiedResidual(
3356 sym - rescaled, sym.cwiseAbs() + rescaled_abs, 3);
3358 Eigen::MatrixXd eq_double = equilibrated.cast<
double>();
3359 eq_double = 0.5 * (eq_double + eq_double.transpose());
3360 Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> es =
3361 timedSymmetricEigen(eq_double);
3362 if (es.info() != Eigen::Success ||
3363 es.eigenvalues().size() != n ||
3364 !es.eigenvalues().allFinite() ||
3365 !es.eigenvectors().allFinite()) {
3366 throw BorderedVarianceError(
3367 "the bordered kernel eigendecomposition "
3371 const ExtendedVector evals_asc =
3372 es.eigenvalues().cast<Extended>();
3373 const ExtendedMatrix evecs_asc =
3374 es.eigenvectors().cast<Extended>();
3375 const Extended lambda_max = evals_asc(n - 1);
3376 const Extended lambda_min = evals_asc(0);
3377 if (!(lambda_max > Extended(0)) ||
3378 !workingIsFinite(lambda_max) ||
3379 !workingIsFinite(lambda_min)) {
3380 throw BorderedVarianceError(
3381 "the kernel matrix is not positive "
3387 const Extended es_residual = certifiedResidual(
3388 equilibrated - evecs_asc * evals_asc.asDiagonal() *
3389 evecs_asc.transpose(),
3390 equilibrated.cwiseAbs() +
3391 evecs_asc.cwiseAbs() *
3392 evals_asc.cwiseAbs().asDiagonal() *
3393 evecs_asc.transpose().cwiseAbs(),
3394 static_cast<long long>(n) + 2);
3397 const Extended orth_residual = certifiedResidual(
3398 ExtendedMatrix::Identity(n, n) -
3399 evecs_asc.transpose() * evecs_asc,
3400 ExtendedMatrix::Identity(n, n) +
3401 evecs_asc.transpose().cwiseAbs() *
3402 evecs_asc.cwiseAbs(),
3403 static_cast<long long>(n) + 1);
3404 if (!(orth_residual < Extended(1)) ||
3405 !workingIsFinite(es_residual) ||
3406 !workingIsFinite(orth_residual)) {
3407 throw BorderedVarianceError(
3408 "the bordered kernel eigenbasis is not "
3412 Eigen::Index rk = 0;
3413 while (rk < n && evals_asc(n - 1 - rk) > 0.0L)
3416 throw BorderedVarianceError(
3417 "the kernel matrix has no positive "
3421 const gpr::extended::FormedFactor<Extended> formed =
3423 diag_scale, evecs_asc, evals_asc, rk,
3424 kFormedFactorEntryOps);
3426 throw BorderedVarianceError(
3427 "the bordered factor entries exceed "
3428 "working-precision resolution");
3430 const ExtendedMatrix& B = formed.
B;
3431 Eigen::HouseholderQR<ExtendedMatrix> qr(B);
3433 qr.householderQ() * ExtendedMatrix::Identity(n, rk);
3436 .topLeftCorner(rk, rk)
3437 .template triangularView<Eigen::Upper>();
3439 const Extended qr_residual = certifiedResidual(
3440 B - factor->Q * factor->R,
3442 factor->Q.cwiseAbs() * factor->R.cwiseAbs(),
3443 static_cast<long long>(rk) + 1);
3444 factor->q_orth_res = certifiedResidual(
3445 ExtendedMatrix::Identity(rk, rk) -
3446 factor->Q.transpose() * factor->Q,
3447 ExtendedMatrix::Identity(rk, rk) +
3448 factor->Q.transpose().cwiseAbs() *
3449 factor->Q.cwiseAbs(),
3450 static_cast<long long>(n) + 1);
3451 if (!(factor->q_orth_res < Extended(1)) ||
3452 !workingIsFinite(qr_residual) ||
3453 !workingIsFinite(factor->q_orth_res)) {
3454 throw BorderedVarianceError(
3455 "the bordered QR factor is ill-conditioned");
3457 factor->q_norm_f = factor->Q.norm();
3459 workingSqrt(Extended(1) + factor->q_orth_res);
3460 const Extended r_norm_f = factor->R.norm();
3461 factor->r_norm_f2 = r_norm_f * r_norm_f;
3463 const Extended max_d2 = max_d * max_d;
3464 const Extended neg_eval =
3465 lambda_min < 0.0L ? -lambda_min : 0.0L;
3466 const Extended eps_pos =
3468 (es_residual + (1.0L + orth_residual) * neg_eval);
3469 const long long b_entries =
3470 static_cast<long long>(B.size());
3471 if (b_entries > (1LL << 26)) {
3472 throw BorderedVarianceError(
3473 "the bordered factor exceeds the eps_K "
3476 const Extended eps_qr =
3477 qr_residual * (2.0L * formed.
norm + qr_residual);
3482 const long long eps_k_ops =
3484 std::max<long long>(
3487 std::max(kEpsQrExtraOps, kEpsBbExtraOps));
3488 factor->eps_k = directedUpper(
3489 static_cast<Extended
>(bordered_assembly_error_) +
3490 sym_residual + scale_residual + eps_pos +
3493 factor->eps_k_ops =
static_cast<int>(eps_k_ops);
3494 factor->lambda_min_cert = directedLower(
3495 (rk == n && min_pos_d > Extended(0) &&
3496 lambda_min > Extended(0))
3497 ? lambda_min * (Extended(1) - orth_residual) *
3498 min_pos_d * min_pos_d
3504 throw BorderedVarianceError(
3505 "bordered variance requires an exact stored kernel");
3507 bordered_cache_.factor = std::move(factor);
3508 ++bordered_cache_.builds;
3509 }
catch (
const BorderedVarianceError& err) {
3510 bordered_cache_.error = err.what();
3512 }
catch (
const std::exception& err) {
3513 bordered_cache_.error = err.what();
3514 throw BorderedVarianceError(err.what());
3519std::pair<std::shared_ptr<const StableBasisND::BorderedFactorCache>,
3520 std::shared_ptr<const StableBasisND::BorderedRmCache>>
3521StableBasisND::ensureBorderedFactorAndRm(
double sigma2)
const
3524 using ExtendedMatrix =
3525 Eigen::Matrix<Extended, Eigen::Dynamic, Eigen::Dynamic>;
3527 if (!(sigma2 >= 0.0) || !std::isfinite(sigma2)) {
3528 throw BorderedVarianceError(
3529 "bordered variance inputs do not match the stable basis");
3532 std::lock_guard<std::mutex> lock(bordered_cache_.mutex);
3533 buildBorderedFactorLocked();
3535 const auto factor = bordered_cache_.factor;
3536 if (!factor->is_kernel_path) {
3537 throw BorderedVarianceError(
3538 "bordered variance requires an exact stored kernel");
3543 const Extended sigma2_ext(sigma2);
3544 const Extended mu_raw =
3545 sigma2_ext + factor->lambda_min_cert - factor->eps_k;
3546 const Extended mu_min = directedLower(mu_raw, kMuMinOps);
3547 if (!(mu_min > Extended(0)) || !workingIsFinite(mu_min)) {
3548 throw BorderedVarianceError(
3549 "the bordered covariance is not certified positive definite at "
3550 "this noise level");
3553 if (!bordered_cache_.rm || bordered_cache_.rm->sigma2 != sigma2) {
3554 auto rm_cache = std::make_shared<BorderedRmCache>();
3555 rm_cache->sigma2 = sigma2;
3556 rm_cache->mu_min = mu_min;
3557 const Eigen::Index rk = factor->rk;
3559 Extended residual = 0;
3561 ExtendedMatrix stacked = ExtendedMatrix::Zero(2 * rk, rk);
3562 stacked.topRows(rk) = factor->R.transpose();
3563 const Extended s_sig = workingSqrt(sigma2_ext);
3564 for (Eigen::Index i = 0; i < rk; ++i)
3565 stacked(rk + i, i) = s_sig;
3566 Eigen::HouseholderQR<ExtendedMatrix> stacked_qr(stacked);
3567 rm_cache->Rm = stacked_qr.matrixQR()
3568 .topLeftCorner(rk, rk)
3569 .template triangularView<Eigen::Upper>();
3570 residual = certifiedResidual(
3571 factor->R * factor->R.transpose() +
3572 sigma2_ext * ExtendedMatrix::Identity(rk, rk) -
3573 rm_cache->Rm.transpose() * rm_cache->Rm,
3574 factor->R.cwiseAbs() * factor->R.transpose().cwiseAbs() +
3575 sigma2_ext * ExtendedMatrix::Identity(rk, rk) +
3576 rm_cache->Rm.transpose().cwiseAbs() *
3577 rm_cache->Rm.cwiseAbs(),
3578 gramResidualEntryOps(rk));
3584 Eigen::HouseholderQR<ExtendedMatrix> transpose_qr(
3585 factor->R.transpose());
3586 rm_cache->Rm = transpose_qr.matrixQR()
3587 .topLeftCorner(rk, rk)
3588 .template triangularView<Eigen::Upper>();
3589 residual = certifiedResidual(
3590 factor->R * factor->R.transpose() -
3591 rm_cache->Rm.transpose() * rm_cache->Rm,
3592 factor->R.cwiseAbs() * factor->R.transpose().cwiseAbs() +
3593 rm_cache->Rm.transpose().cwiseAbs() *
3594 rm_cache->Rm.cwiseAbs(),
3595 gramResidualEntryOps(rk));
3597 rm_cache->rm_residual = residual;
3598 rm_cache->rm_norm_2 = rm_cache->Rm.norm();
3600 bordered_cache_.rm = std::move(rm_cache);
3603 return {factor, bordered_cache_.rm};
3606StableBasisND::TrainingNoiseReport StableBasisND::borderedTrainingNoiseReport(
3607 double sigma2)
const
3609 if (!(sigma2 >= 0.0) || !std::isfinite(sigma2)) {
3610 throw BorderedVarianceError(
3611 "bordered variance inputs do not match the stable basis");
3613 TrainingNoiseReport
out;
3614 out.requested = sigma2;
3615 out.floored = conditionFlooredSigma2(Sr_, sigma2, Psi_.rows());
3616 out.floor_active =
out.floored > sigma2;
3618 std::lock_guard<std::mutex> lock(bordered_cache_.mutex);
3619 if (!extendedCertificationEnabledLocked())
return out;
3620 buildBorderedFactorLocked();
3621 const auto factor = bordered_cache_.factor;
3623 const Extended gap_raw = factor->eps_k - factor->lambda_min_cert;
3624 const Extended gap_hi =
3625 gpr::extended::WorkingPrecision<Extended>::nextUp(gap_raw);
3627 out.certifiable =
true;
3637 double sigma2,
double output_variance_scale)
const
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");
3644 const TrainingNoiseReport training = borderedTrainingNoiseReport(sigma2);
3656 if (!training.certifiable) {
3664 double gap_down = 0.0;
3673 double calibration)
const
3679 throw BorderedVarianceError(
3680 "bordered variance inputs do not match the stable basis");
3682 const TrainingNoiseReport training = borderedTrainingNoiseReport(sigma2);
3689 if (!training.certifiable) {
3700std::vector<BorderedVarianceInterval>
3702 const Eigen::VectorXd& prior_diag,
3703 double sigma2)
const
3709std::vector<BorderedVarianceInterval>
3711 const Eigen::VectorXd& prior_diag,
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");
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");
3732 std::vector<BorderedVarianceInterval> intervals(
3733 static_cast<std::size_t
>(rhs.cols()));
3734 if (rhs.cols() == 0)
return intervals;
3736 const auto [factor, rm_cache] = ensureBorderedFactorAndRm(sigma2);
3737 sigma2 = rm_cache->sigma2;
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 =
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");
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);
3761 const Extended w_lo =
3762 (sigma2 > 0.0) ? (Extended(1) / sigma2_ext) : Extended(0);
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;
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();
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);
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;
3787 q_k_perp = (factor->Q.transpose() * k_perp).norm();
3790 rm_cache->Rm.transpose()
3791 .template triangularView<Eigen::Lower>()
3794 rm_cache->Rm.template triangularView<Eigen::Upper>().solveInPlace(
3796 v_q = -(factor->Q * alpha);
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;
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;
3815 for (Eigen::Index row = 0; row < rk; ++row)
3816 neumaier_add(-w_q(row) * w_q(row));
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");
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);
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() *
3838 const Extended delta_w =
3839 (rk > 0) ? gamma_r_work *
3840 (rm_cache->Rm.cwiseAbs() * alpha.cwiseAbs()).norm()
3842 const Extended rho_solve = rm_cache->rm_norm_2 * delta_w + delta_y;
3844 const Extended e_split_q = directedUpper(
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),
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,
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),
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);
3871 const Extended r_perp = (sigma2 > 0.0) ? Extended(0) : k_perp_norm;
3872 const Extended r_norm = directedUpper(
3875 (rho_solve + rm_cache->rm_residual * alpha_norm +
3877 (factor->q_orth_res * alpha_norm + w_lo * q_k_perp)) +
3878 r_perp + factor->eps_k * v_norm,
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");
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");
3896 if (!(raw_hi >= Extended(0))) {
3897 throw BorderedVarianceError(
3898 "the bordered variance upper bound is negative");
3900 if (raw_lo < Extended(0)) raw_lo = Extended(0);
3905 throw BorderedVarianceError(
3906 "bordered variance interval endpoints are inconsistent");
3908 intervals[
static_cast<std::size_t
>(column)] = {lo, hi};
3919 sigma2 = conditionFlooredSigma2(Sr_, sigma2, Psi_.rows());
3920 if (Psi_.rows() == 0 || Psi_.cols() != Sr_.size() || !(sigma2 > 0.0)) {
3921 return Eigen::VectorXd();
3924 const Eigen::ArrayXd shrink =
3925 Sr_.array().square() / (Sr_.array().square() + 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();
3942 const Eigen::VectorXi& rows,
double sigma2)
const
3946 sigma2 = conditionFlooredSigma2(Sr_, sigma2, Psi_.rows());
3947 if (Psi_.rows() == 0 || Psi_.cols() != Sr_.size() || !(sigma2 > 0.0)) {
3948 return Eigen::VectorXd();
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();
3962 for (Eigen::Index j = 0; j < Psi_.cols(); ++j) {
3963 const double inv_noisy = 1.0 / (Sr_(j) * Sr_(j) + sigma2);
3975 const Eigen::VectorXd&
y,
double sigma2)
const
3977 if (
y.size() != Psi_.rows() || !(sigma2 > 0.0)) {
3978 return std::numeric_limits<double>::quiet_NaN();
3981 const Eigen::VectorXd alpha =
solveNoisy(
y, sigma2);
3983 if (alpha.size() !=
y.size() || inv_diag.size() !=
y.size()) {
3984 return std::numeric_limits<double>::quiet_NaN();
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();
3994 nlp += 0.5 * (log_two_pi - std::log(q) + alpha(i) * alpha(i) / q);
4000 const Eigen::VectorXd& diagonal)
4002 if (alpha.size() < 2 || alpha.size() != diagonal.size())
return false;
4007 constexpr double kChiSquare1Median = 0.4549364231195727;
4008 const double limit = std::sqrt(kChiSquare1Median) *
4009 (1.0 - 128.0 * std::numeric_limits<double>::epsilon());
4010 Eigen::Index below = 0;
4011 for (Eigen::Index i = 0; i < alpha.size(); ++i) {
4012 if (!std::isfinite(alpha(i)) || !std::isfinite(diagonal(i)) ||
4013 !(diagonal(i) > 0.0))
4015 if (std::abs(alpha(i)) * diagonal(i) < limit) ++below;
4017 return below > alpha.size() / 2;
4021 const Eigen::VectorXd& inv_diag)
4032 if (alpha.size() < 2 || alpha.size() != inv_diag.size())
return 1.0;
4033 std::vector<double> z2;
4034 z2.reserve(
static_cast<std::size_t
>(alpha.size()));
4035 for (Eigen::Index i = 0; i < alpha.size(); ++i) {
4036 const double q = inv_diag(i);
4037 if (!(q > 0.0) || !std::isfinite(q) || !std::isfinite(alpha(i)))
4039 z2.push_back(alpha(i) * alpha(i) / q);
4041 std::sort(z2.begin(), z2.end());
4042 const std::size_t n = z2.size();
4043 const double median_z2 =
4044 (n % 2 == 1) ? z2[n / 2] : 0.5 * (z2[n / 2 - 1] + z2[n / 2]);
4045 constexpr double kChiSquare1Median = 0.4549364231195727;
4046 const double c = median_z2 / kChiSquare1Median;
4047 return (std::isfinite(c) && c > 1.0) ? c : 1.0;
4051 double sigma2)
const
4053 if (
y.size() < 2 ||
y.size() != Psi_.rows())
return 1.0;
4054 const Eigen::VectorXd alpha =
solveNoisy(
y, sigma2);
4060 const Eigen::MatrixXd& dK,
double sigma2)
const
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();
4072 if (Psi_.cols() == Psi_.rows()) {
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();
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();
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();
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();
4102 return inv_noise * inv_noise * (dK.diagonal() - left - right + low_rank);
4107 const Eigen::VectorXd&
y,
double sigma2,
const Eigen::MatrixXd& dK)
const
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();
4114 const Eigen::VectorXd alpha =
solveNoisy(
y, sigma2);
4116 const Eigen::VectorXd dalpha = -
solveNoisy(dK * alpha, 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();
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();
4131 0.5 * ((-1.0 / q - alpha(i) * alpha(i) / (q * q)) * dq(i) +
4132 2.0 * alpha(i) * dalpha(i) / q);
4139 sigma2 = conditionFlooredSigma2(Sr_, sigma2, Psi_.rows());
4142 const Eigen::Index n = Psi_.rows();
4143 if (n == 0 || Psi_.cols() != Sr_.size() || !(sigma2 > 0.0)) {
4144 return Eigen::MatrixXd();
4146 const Eigen::ArrayXd mu =
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();
4157 const Eigen::VectorXd&
y,
double sigma2,
4158 const std::vector<std::vector<Eigen::Index>>& groups)
const
4160 if (
y.size() != Psi_.rows() || !(sigma2 > 0.0)) {
4161 return std::numeric_limits<double>::quiet_NaN();
4163 const Eigen::VectorXd alpha =
solveNoisy(
y, sigma2);
4164 if (alpha.size() !=
y.size()) {
4165 return std::numeric_limits<double>::quiet_NaN();
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();
4179 const Eigen::ArrayXd mu =
4181 : Eigen::ArrayXd(Sr_.array().square() + sig_f);
4185 const Eigen::ArrayXd d = mu.inverse() - q;
4186 const double log_two_pi = std::log(2.0 * std::acos(-1.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);
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)];
4196 PB.row(r) = Psi_.row(idx);
4199 (PB * d.matrix().asDiagonal()) * PB.transpose();
4200 M.diagonal().array() += q;
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);
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);
4225 const Eigen::VectorXd&
y,
double sigma2,
const Eigen::MatrixXd& dK,
4226 const std::vector<std::vector<Eigen::Index>>& groups)
const
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();
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();
4257 const Eigen::ArrayXd mu =
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_;
4263 const Eigen::MatrixXd G = Psi_.transpose() * dKP;
4264 const Eigen::MatrixXd R = dKP - Psi_ * G;
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();
4272 const Eigen::MatrixXd MinvGMinv =
4273 minv.asDiagonal() * G * minv.asDiagonal();
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)];
4283 daB(r) = dalpha(gr);
4284 PB.row(r) = Psi_.row(gr);
4285 RB.row(r) = R.row(gr);
4287 Eigen::MatrixXd M = (PB * dvec.asDiagonal()) * PB.transpose();
4288 M.diagonal().array() += q;
4289 const Eigen::MatrixXd PBMinv = PB * minv.asDiagonal();
4290 const Eigen::MatrixXd cross = RB * PBMinv.transpose();
4291 const Eigen::MatrixXd dM =
4292 -(PB * MinvGMinv * PB.transpose() +
4293 q * (cross + cross.transpose()));
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;
4306 const double dlogdet = -(Sig * dM).trace();
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);
4319 sigma2 = conditionFlooredSigma2(Sr_, sigma2, Psi_.rows());
4323 const Eigen::Index nobs = Psi_.rows();
4325 double ld = (Sr_.array().square() + sigma2).log().sum();
4326 ld +=
static_cast<double>(nobs - rank_) * std::log(sigma2);
4331 const Eigen::VectorXd& alpha)
const
4334 Psi_.cols() == Psi_.rows() || alpha.size() != Psi_.rows())
4336 Eigen::VectorXd coefficients = Psi_.transpose() * alpha;
4337 coefficients += Psi_.transpose() * (alpha - Psi_ * coefficients);
4338 return Psi_ * coefficients;
4342 const Eigen::MatrixXd& Xstar,
const Eigen::VectorXd& alpha)
const
4346 Eigen::MatrixXd A_E;
4347 std::vector<Eigen::MatrixXd> A_g;
4348 designAt(Xstar, A_E, A_g);
4349 const Eigen::VectorXd v =
4355 const Eigen::MatrixXd& Xstar,
const Eigen::VectorXd& alpha)
const
4357 Eigen::MatrixXd A_E;
4358 std::vector<Eigen::MatrixXd> A_g;
4359 designAt(Xstar, A_E, A_g);
4360 const Eigen::VectorXd v =
4362 Eigen::MatrixXd G(Xstar.rows(), dim_);
4363 for (
int j = 0; j < dim_; ++j)
4364 G.col(j) = A_g[j] * v;
4370 if (covariance.rows() != covariance.cols() || !covariance.allFinite())
4372 const Eigen::VectorXd diagonal = covariance.diagonal();
4373 if ((diagonal.array() < 0.0).any())
return false;
4374 if (covariance.rows() <= 1)
return true;
4379 const auto geometric_mean = [](
double left,
double right)
noexcept {
4380 if (!(left > 0.0) || !(right > 0.0))
return 0.0;
4381 return std::sqrt(left) * std::sqrt(right);
4399 Eigen::MatrixXd correlation =
4400 Eigen::MatrixXd::Identity(covariance.rows(), covariance.cols());
4401 for (Eigen::Index column = 0; column < covariance.cols(); ++column) {
4402 for (Eigen::Index row = 0; row < column; ++row) {
4403 const double scale =
4404 geometric_mean(diagonal(row), diagonal(column));
4405 if (!std::isfinite(scale))
return false;
4407 if (!(scale > 0.0)) {
4408 if (covariance(row, column) != 0.0)
return false;
4410 value = covariance(row, column) / scale;
4411 if (!std::isfinite(value))
return false;
4413 correlation(row, column) = value;
4414 correlation(column, row) = value;
4417 Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> solver(correlation);
4418 if (solver.info() != Eigen::Success)
return false;
4419 const Eigen::VectorXd raw_eigenvalues = solver.eigenvalues();
4420 if (!raw_eigenvalues.allFinite())
return false;
4421 const double eps = std::numeric_limits<double>::epsilon();
4422 const double rows =
static_cast<double>(correlation.rows());
4424 constexpr double correlation_norm = 1.0;
4425 const double backward_constant = 1.0 / std::sqrt(eps);
4426 const double tolerance = backward_constant * rows * eps * correlation_norm;
4427 if (!std::isfinite(tolerance) ||
4428 !(raw_eigenvalues.minCoeff() >= -tolerance))
4430 const Eigen::VectorXd eigenvalues = raw_eigenvalues.cwiseMax(0.0);
4431 correlation = solver.eigenvectors() * eigenvalues.asDiagonal() *
4432 solver.eigenvectors().transpose();
4433 const Eigen::VectorXd norm =
4434 correlation.diagonal().cwiseMax(0.0).cwiseSqrt();
4435 if ((norm.array() <= 0.0).any())
return false;
4436 for (Eigen::Index column = 0; column < covariance.cols(); ++column) {
4437 for (Eigen::Index row = 0; row < column; ++row) {
4438 const double norm_scale = norm(row) * norm(column);
4439 if (!(norm_scale > 0.0) || !std::isfinite(norm_scale))
return false;
4441 std::clamp(correlation(row, column) / norm_scale, -1.0, 1.0);
4442 const double scale =
4443 geometric_mean(diagonal(row), diagonal(column));
4444 if (!std::isfinite(scale) || !std::isfinite(rho))
return false;
4445 covariance(row, column) = rho * scale;
4446 covariance(column, row) = covariance(row, column);
4447 if (!std::isfinite(covariance(row, column)))
return false;
4450 covariance.diagonal() = diagonal;
4451 if (!covariance.allFinite())
return false;
4456 const Eigen::MatrixXd& cross,
const Eigen::VectorXd& prior,
4457 double sigma2)
const
4459 sigma2 = varianceFlooredSigma2(Sr_, sigma2, Psi_.rows());
4460 if (cross.rows() != Psi_.rows() || prior.size() != cross.cols() ||
4461 Psi_.cols() != Sr_.size())
4463 "stable posterior variance: cross covariance does not match the "
4465 if (!(sigma2 > 0.0) || !std::isfinite(sigma2))
4467 "stable posterior variance: noise floor is not finite and "
4470 Eigen::MatrixXd projected, residual;
4471 projectOntoStableBasis(Psi_, cross, projected, residual);
4476 const bool use_complement = dropped_s2_max_ > 0.0;
4478 Eigen::VectorXd variance(prior.size());
4479 for (Eigen::Index column = 0; column < cross.cols(); ++column) {
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);
4490 const Eigen::MatrixXd& prior,
4491 double sigma2)
const
4493 if (prior.rows() != prior.cols() || prior.rows() != cross.cols())
4495 "stable posterior covariance: prior and query columns disagree");
4496 const Eigen::VectorXd diagonal =
4498 sigma2 = varianceFlooredSigma2(Sr_, sigma2, Psi_.rows());
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)))
4506 "stable posterior covariance: retained singular value is not "
4507 "finite and positive");
4508 retained.row(mode) /= Sr_(mode);
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_))
4515 "stable posterior covariance: complement eigenvalue is not "
4517 complement = residual / std::sqrt(dropped_s2_max_);
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) {
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);
4536 retained(mode, column),
4537 sigma2 / (s2 + sigma2));
4539 if (use_complement) {
4540 const double attenuation = sigma2 / (dropped_s2_max_ + sigma2);
4541 for (Eigen::Index mode = 0; mode < complement.rows(); ++mode) {
4543 complement(mode, column));
4545 complement(mode, column),
4549 covariance(row, column) = value.
value();
4550 covariance(column, row) = covariance(row, column);
4552 covariance(column, column) = diagonal(column);
4558 const Eigen::MatrixXd& prior,
4559 const Eigen::VectorXd& weights,
4560 double sigma2)
const
4562 if (prior.rows() != prior.cols() || prior.rows() != cross.cols() ||
4563 weights.size() != prior.rows() || cross.rows() != Psi_.rows() ||
4564 Psi_.cols() != Sr_.size())
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))
4571 "stable posterior action variance: noise floor is not finite and "
4574 Eigen::MatrixXd action(cross.rows(), 1);
4575 for (Eigen::Index row = 0; row < cross.rows(); ++row) {
4577 for (Eigen::Index column = 0; column < cross.cols(); ++column)
4578 value.
addProduct(cross(row, column), weights(column));
4579 action(row, 0) = value.
value();
4581 Eigen::MatrixXd projected, residual;
4582 projectOntoStableBasis(Psi_, action, projected, residual);
4585 for (Eigen::Index column = 0; column < prior.cols(); ++column)
4586 for (Eigen::Index row = 0; row < prior.rows(); ++row)
4589 return nonnegativeEigenmodeVariance(
4590 projected.col(0), residual.col(0), Sr_, sigma2,
4599double affineResidualTail(
double squared_radius)
4604 const double x = 2.0 * squared_radius;
4605 if (
x >= 48.0)
return 1.0;
4606 if (
x >= 1.0 / 16.0)
return std::fma(-
x, std::exp(-
x), -std::expm1(-
x));
4613 for (
int k = 1; k <= 8; ++k) {
4614 term *= -
x * (k + 1) / (k * (k + 2));
4621Eigen::VectorXd StableBasisND::rangeVarianceFromDesign(
4622 const Eigen::MatrixXd& A_E,
double sigma2,
4623 const AffineVariancePrior* affine_prior)
const
4625 sigma2 = conditionFlooredSigma2(Sr_, sigma2, Psi_.rows());
4626 const Eigen::Index m = A_E.rows();
4627 if (!(sigma2 > 0.0) || !std::isfinite(sigma2)) {
4628 throw BorderedVarianceError(
4629 "design variance requires a strictly positive noise variance");
4631 if (affine_prior && affine_prior->diagonal.size() != m) {
4632 throw BorderedVarianceError(
4633 "exact prior diagonal size mismatch in design variance");
4635 using Extended = DesignVarianceReal;
4636 using ExtendedMatrix =
4637 Eigen::Matrix<Extended, Eigen::Dynamic, Eigen::Dynamic>;
4638 using ExtendedVector = Eigen::Matrix<Extended, Eigen::Dynamic, 1>;
4639 const Extended sigma2_ext =
static_cast<Extended
>(sigma2);
4640 const Extended s_sig = workingSqrt(sigma2_ext);
4641 const ExtendedMatrix A_train_ext = A_train_.cast<Extended>();
4642 const Eigen::Index nobs = A_train_ext.rows();
4643 const Eigen::Index N = A_train_ext.cols();
4645 ExtendedMatrix stacked(N + nobs, nobs);
4646 stacked.topRows(N) = A_train_ext.transpose();
4647 stacked.bottomRows(nobs) = s_sig * ExtendedMatrix::Identity(nobs, nobs);
4648 Eigen::HouseholderQR<ExtendedMatrix> qr(stacked);
4649 const ExtendedMatrix R_m = qr.matrixQR()
4650 .topLeftCorner(nobs, nobs)
4651 .template triangularView<Eigen::Upper>();
4659 Eigen::VectorXd var(m);
4660 for (Eigen::Index i = 0; i < m; ++i) {
4661 const ExtendedVector a_star = A_E.row(i).transpose().cast<Extended>();
4662 const ExtendedVector ks = A_train_ext * a_star;
4663 ExtendedVector w = ks;
4664 R_m.transpose().template triangularView<Eigen::Lower>().solveInPlace(w);
4665 ExtendedVector u = w;
4666 R_m.template triangularView<Eigen::Upper>().solveInPlace(u);
4667 const ExtendedVector res = a_star - A_train_ext.transpose() * u;
4668 Extended value = res.squaredNorm() + sigma2_ext * u.squaredNorm();
4670 Extended missing = affine_prior->diagonal(i);
4671 if (!affine_prior->stable) {
4672 const Extended a_norm2 = a_star.squaredNorm();
4673 if (!(missing >= a_norm2)) {
4674 throw BorderedVarianceError(
4675 "affine prior diagonal is smaller than its truncated "
4679 }
else if (!(missing >= Extended(0)) || !workingIsFinite(missing)) {
4680 throw BorderedVarianceError(
4681 "unrepresented prior variance is negative or nonfinite");
4691 const Eigen::MatrixXd& Xstar,
double sigma2)
const
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);
4700 const Eigen::MatrixXd& Ustar,
const Eigen::MatrixXd& residuals,
4701 double sigma2)
const
4703 Eigen::MatrixXd A_E;
4704 AffineVariancePrior affine_prior;
4705 designAtAffineEnergy(Ustar, residuals, A_E, &affine_prior);
4706 if (affine_prior.stable) {
4710 for (Eigen::Index i = 0; i < affine_prior.diagonal.size(); ++i)
4711 affine_prior.diagonal(i) *= DesignVarianceReal(
4712 affineResidualTail(residuals.row(i).squaredNorm()));
4714 return rangeVarianceFromDesign(A_E, sigma2, &affine_prior);
4719 return condition_number_;
4725 if (Psi_.size() == 0 || Sr_.size() == 0)
return Eigen::MatrixXd();
4727 return Psi_ * Sr_.array().square().matrix().asDiagonal() *
4731 if (A_train_.size() == 0)
return Eigen::MatrixXd();
4732 return A_train_ * A_train_.transpose();
4749inline constexpr long long kLatentTermChainOps = 6;
4750inline constexpr long long kLatentAssemblyOps = 4;
4755inline constexpr long long kLatentMagnitudeAssemblyOps = 3;
4757long long latentMagnitudeOperationDepth(Eigen::Index rank)
4759 return kLatentTermChainOps +
static_cast<long long>(rank) +
4760 kLatentMagnitudeAssemblyOps;
4763long long latentVarianceOperationDepth(Eigen::Index rank)
4765 const long long reduction = rank > 0 ?
static_cast<long long>(rank) - 1 : 0;
4766 return kLatentTermChainOps + reduction + kLatentAssemblyOps;
4773std::atomic<long long> g_schur_floored{0};
4774std::atomic<long long> g_schur_proven_negative{0};
4775std::atomic<long long> g_schur_uncertified{0};
4776std::atomic<long long> g_schur_raised{0};
4781 g_schur_floored.fetch_add(report.floored, std::memory_order_relaxed);
4782 if (report.proven_negative)
4783 g_schur_proven_negative.fetch_add(report.proven_negative,
4784 std::memory_order_relaxed);
4785 if (report.uncertified)
4786 g_schur_uncertified.fetch_add(report.uncertified,
4787 std::memory_order_relaxed);
4789 g_schur_raised.fetch_add(report.raised, std::memory_order_relaxed);
4795 Eigen::Index
rank)
noexcept
4797 return latentVarianceOperationDepth(
rank);
4802 return std::numeric_limits<DesignVarianceReal>::digits;
4806 const Eigen::MatrixXd& A_E,
double sigma2)
const
4808 return rangeVarianceFromDesign(A_E, sigma2);
4812 int& operations)
const
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;
4826 totals.
floored = g_schur_floored.load(std::memory_order_relaxed);
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);
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);
4843 const Eigen::MatrixXd& cross,
const Eigen::VectorXd& prior,
double sigma2,
4844 Eigen::VectorXd& value,
const std::vector<char>* skip)
const
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();
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) {
4860 }
else if (value(i) < 0.0) {
4861 if (!cross.col(i).allFinite() || !std::isfinite(prior(i))) {
4865 negative.push_back(i);
4869 if (!negative.empty()) {
4870 std::vector<BorderedVarianceInterval> intervals;
4871 bool enclosed =
false;
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)]);
4883 rhs, prior_subset, sigma2,
4885 enclosed = intervals.size() == negative.size();
4886 }
catch (
const std::runtime_error&) {
4890 for (std::size_t k = 0; k < negative.size(); ++k) {
4891 double& entry = value(negative[k]);
4895 }
else if (intervals[k].upper < 0.0) {
4898 }
else if (intervals[k].lower <= 0.0) {
4906 entry = intervals[k].lower;
4911 recordSchurFloor(report);
4916 Eigen::Index row,
double statistical_sigma2)
const
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))
4924 const Eigen::Index
rank = Psi_.cols();
4925 const Extended eta2(statistical_sigma2);
4926 const Extended complement(
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);
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);
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);
4959 }
catch (
const BorderedVarianceError&) {
4967 if (latent >= 0.0)
return latent;
4968 const double inf = std::numeric_limits<double>::infinity();
4970 double result = inf;
4971 if (!std::isfinite(latent) || !std::isfinite(error_bound) ||
4972 !(error_bound >= 0.0))
4974 else if (latent + error_bound >= 0.0) {
4979 recordSchurFloor(local);
4981 report->floored += local.
floored;
Implementation-independent symmetric eigenpairs.
Runtime-dlopen'd cuSOLVER dense symmetric eigensolver (syevd).
Correctly rounded Schur-complement diagonals from Cholesky solves.
Exact floating-point accumulator (Kulisch long accumulator).
void dsyevr_(char *, char *, char *, int *, double *, int *, double *, double *, int *, int *, double *, int *, double *, double *, int *, int *, double *, int *, int *, int *, int *)
void factorize(const Eigen::VectorXd &x, double eps, double alpha, int n_extra=20, double sv_rtol=1e-13)
Eigen::VectorXd predict(const Eigen::VectorXd &xstar, const Eigen::VectorXd &b) const
double conditionNumber() const
void eigenfunctionsWithEpsDerivative(const Eigen::VectorXd &x, Eigen::MatrixXd &Phi, Eigen::MatrixXd &dPhi_deps) const
Eigen::VectorXd sqrtLambdaEpsDerivative() const
Eigen::VectorXd solve(const Eigen::VectorXd &y) const
Eigen::MatrixXd evalBasis(const Eigen::VectorXd &xstar) const
static double conditionFlooredSigma2ForTesting(const Eigen::VectorXd &singular_values, double sigma2, Eigen::Index nobs)
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)
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 noisyInverseSandwichDiagonal(const Eigen::MatrixXd &dK, double sigma2) const
static void resetSchurFloorTotals() noexcept
void borderedEpsKForTesting(double &hi, double &lo, int &operations) const
double conditionNumber() const
static bool gradedModeCountExceedsLimit(int dim, int max_degree, Eigen::Index limit)
static Eigen::MatrixXd affineSpanBasis(const Eigen::MatrixXd ¢ered_X)
bool hasNoisyEigenvalues() const
static int capMaxDegreeByModeCount(int dim, int requested_degree, Eigen::Index mode_limit)
Eigen::VectorXd posteriorMeanWeights(const Eigen::VectorXd &alpha) const
Eigen::VectorXd posteriorVarianceDiagonal(const Eigen::MatrixXd &cross, const Eigen::VectorXd &prior, double sigma2) const
Cancellation-free posterior diagonal for arbitrary query channels.
double covarianceComplementEigenvalue() const noexcept
Largest signal eigenvalue represented by the discarded covariance complement.
Eigen::VectorXd noisySelfQuadratic(const Eigen::MatrixXd &rhs, double sigma2) const
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)
bool permuteObservationRows(const Eigen::VectorXi &source_for_target)
double varianceFlooredNoise(double sigma2) const
Variance-specific likelihood-noise floor for the retained spectrum.
static SchurFloorReport schurFloorTotals() noexcept
Process-wide totals of SchurFloorReport over every call.
Eigen::MatrixXd predictGradientAffine(const Eigen::MatrixXd &Ustar, const Eigen::MatrixXd &residuals, const Eigen::MatrixXd &basis, const Eigen::VectorXd &b) 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.
static int designVarianceWorkingDigitsForTesting() noexcept
double logDetNoisy(double sigma2) const
Eigen::VectorXd predictEnergy(const Eigen::MatrixXd &Xstar, const Eigen::VectorXd &b) const
Eigen::VectorXd posteriorMeanReducedCoeffs(const Eigen::VectorXd &y, double sigma2) const
void factorizeNoisyKernel(const Eigen::MatrixXd &noisy_kernel, double sigma2)
Eigen::VectorXd predictEnergyAffine(const Eigen::MatrixXd &Ustar, const Eigen::MatrixXd &residuals, const Eigen::VectorXd &b) const
Eigen::VectorXd noisyInverseDiagonal(double sigma2) const
Eigen::MatrixXd posteriorMeanGradient(const Eigen::MatrixXd &Xstar, const Eigen::VectorXd &alpha) const
static double floorLatentVariance(double latent, double error_bound, SchurFloorReport *report) noexcept
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 ...
double covarianceComplementWeight(double sigma2) const noexcept
Eigen::VectorXd posteriorMeanEnergy(const Eigen::MatrixXd &Xstar, const Eigen::VectorXd &alpha) const
SchurFloorReport floorCertifiedSchurDiagonal(const Eigen::MatrixXd &cross, const Eigen::VectorXd &prior, double sigma2, Eigen::VectorXd &value, const std::vector< char > *skip=nullptr) const
Eigen::Index borderedKernelOrder() const noexcept
Eigen::VectorXd energyAffineDesignRow(const Eigen::MatrixXd &Ustar, const Eigen::MatrixXd &residuals) const
static long long latentVarianceOperationDepthForTesting(Eigen::Index rank) noexcept
double leaveOneOutNegativeLogPredictiveDensityDirectionalDerivative(const Eigen::VectorXd &y, double sigma2, const Eigen::MatrixXd &dK) const
void factorize(const Eigen::MatrixXd &X, const Eigen::VectorXd &eps, double alpha, int max_degree, bool gradient_enhanced, double sv_rtol=1e-13)
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)
static int autoMaxDegree(const Eigen::VectorXd &eps, double alpha, int dim, double target_tol, int max_degree_cap=40)
double leaveOneOutNegativeLogPredictiveDensityGroupedDirectionalDerivative(const Eigen::VectorXd &y, double sigma2, const Eigen::MatrixXd &dK, const std::vector< std::vector< Eigen::Index > > &groups) const
Eigen::MatrixXd predictGradient(const Eigen::MatrixXd &Xstar, const Eigen::VectorXd &b) const
Eigen::MatrixXd posteriorCovariance(const Eigen::MatrixXd &cross, const Eigen::MatrixXd &prior, double sigma2) const
Joint posterior covariance from the same exact eigenmode sums.
Eigen::VectorXd solve(const Eigen::VectorXd &y) const
double trainingRowLatentErrorBound(Eigen::Index row, double sigma2) 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 noisyRangeSelfQuadratic(const Eigen::MatrixXd &rhs, double sigma2) const
double leaveOneOutNegativeLogPredictiveDensity(const Eigen::VectorXd &y, double sigma2) const
bool supportsBorderedVarianceInterval() const noexcept
void liftFromDeflatedSubspace(Eigen::Index full_rows, Eigen::MatrixXd lifted_psi, const detail::RigidDeflationState &deflation, double extra_assembly_error=0.0)
double complementWeight(double sigma2) const noexcept
Eigen::MatrixXd reconstructKernel(bool truncated) const
const Eigen::MatrixXd & leftSingularVectors() const
bool factorizeNoisyKernelLapackRrr(const Eigen::MatrixXd &noisy_kernel, double sigma2)
Eigen::VectorXd solveNoisy(const Eigen::VectorXd &y, double sigma2) const
std::vector< BorderedVarianceInterval > noisyBorderedVarianceIntervals(const Eigen::MatrixXd &rhs, const Eigen::VectorXd &prior_diag, double sigma2) const
static std::size_t factorizationCount() noexcept
static void projectToAffineSpan(const Eigen::MatrixXd ¢ered_X, const Eigen::MatrixXd &basis, Eigen::MatrixXd &coords, Eigen::MatrixXd &residuals)
Eigen::VectorXd noisyInverseDiagonalEntries(const Eigen::VectorXi &rows, double sigma2) const
void recordDroppedSpectrum(const Eigen::VectorXd &S)
Eigen::VectorXd rangeVarianceFromDesignForTesting(const Eigen::MatrixXd &A_E, double sigma2) const
BorderedNoiseReport borderedNoiseReport(double sigma2) const
double conditionFlooredNoise(double sigma2) const
const Eigen::VectorXd & singularValues() const
void eigenTensorEpsDerivative(const Eigen::MatrixXd &X, int j, Eigen::MatrixXd &Phi, Eigen::MatrixXd &dPhi_eps) const
Eigen::VectorXd posteriorVarianceEnergy(const Eigen::MatrixXd &Xstar, double sigma2) const
static Eigen::Index standardChop(const Eigen::VectorXd &coeffs, double tol)
Eigen::MatrixXd noisyInverse(double sigma2) const
double leaveOneOutNegativeLogPredictiveDensityGrouped(const Eigen::VectorXd &y, double sigma2, const std::vector< std::vector< Eigen::Index > > &groups) const
Eigen::Index numObs() const
StableBasisPosteriorWeights noisyPosteriorWeights(const Eigen::VectorXd &y, double sigma2) const
void factorizeKernel(const Eigen::MatrixXd &kernel, double sv_rtol=1e-13, double sv_abs_tol=0.0, double sv_chop_tol=0.0)
Eigen::VectorXd posteriorVarianceEnergyAffine(const Eigen::MatrixXd &Ustar, const Eigen::MatrixXd &residuals, double sigma2) const
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)
double computeVarianceCalibrationFactor(const Eigen::VectorXd &y, double sigma2) const
void assumeExtendedCertificationForTesting(bool available)
static CusolverEighLib & instance()
void addProduct(double a, double b) noexcept
void add(double x) noexcept
double value() const noexcept
The exact sum rounded once to the nearest double, ties to even.
void addTripleProduct(double a, double b, double c) noexcept
Raised when a stable posterior variance is not finite, is materially negative, or its operands do not...
eon_relax_band_t eon_relax_surface_fn void eon_relax_outcome_t * out
bool isfinite(DoubleDouble a)
Work frobeniusResidualUpperBound(const ComputedMatrix &computed, const AbsMatrix &abs_terms, long long entry_ops)
std::conditional_t< nativeLongDoubleIsExtended(), long double, DoubleDouble > WorkingReal
void outwardProduct(double a, double b, double &down, double &up)
double roundDownToDouble(Work value)
FormedFactor< Work > formScaledFactor(const DiagScale &diag_scale, const Vectors &evecs_asc, const Values &evals_asc, Eigen::Index rank, int entry_ops)
DoubleDouble sqrt(DoubleDouble a)
DoubleDouble abs(DoubleDouble a)
VarianceScaleEnclosure< Work > varianceScaleEnclosure(double y_scale, double calibration)
double scaledUpperBound(double value, const VarianceScaleEnclosure< Work > &scale)
constexpr bool certificationAvailable()
bool workingFinite(Work value)
double roundUpToDouble(Work value)
double scaledLowerBound(double value, const VarianceScaleEnclosure< Work > &scale)
constexpr int kDirectedScaleOps
Dense and structured linear algebra behind the GP: Cholesky and eigen solvers, linear operators,...
void canonicalizeEigenpairs(Eigen::Ref< Eigen::VectorXd > evals, Eigen::Ref< Eigen::MatrixXd > evecs)
evals has one entry per leading column of evecs. Both are rewritten.
void requireStablePosteriorVariance(double &variance, double signal_variance, double relative_allowance)
Accept one stable posterior variance or throw.
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 stablePosteriorVarianceEnabled() noexcept
Whether stable posterior variance reductions are enabled.
bool distributed_thin_svd_tsqr(const EigenMatrix &A_local, int nobs, int N, EigenMatrix &U, Eigen::VectorXd &S, EigenMatrix &V, DistributedState &st=DistributedState::instance())
bool unconstrainedLibraryReductions() noexcept
DistributedFactorization distributedFactorization() noexcept
Process-wide selection; Reproducible unless configured otherwise.
bool tryTrainingProduct(ConstProductMatrix a, ConstProductMatrix b, ProductMatrix c, bool transpose_a, bool transpose_b, double alpha, double beta, bool partitioned)
Eigen::Index resolvedSingularRank(const Eigen::VectorXd &singular, double cutoff)
constexpr Eigen::Index kMinDistributedGemmOrder
bool teamDivideConquerEigen(const Eigen::MatrixXd &sym, Eigen::VectorXd &evals, Eigen::MatrixXd &evecs)
bool trainingProductConfigured()
A device library or an in-process engine is configured.
bool covarianceDsyevr(const Eigen::MatrixXd &sym, Eigen::VectorXd &evals, Eigen::MatrixXd &evecs)
constexpr Eigen::Index kMinDistributedSymmetricEigenOrder
double variance(const Weights &w, const Matrix &covariance)
Gaussian-process regression, kernels, priors, and the searches that run on the surrogate.
bool extendSymmetricSpectrum(const Eigen::Ref< const Eigen::MatrixXd > &grown, const Eigen::Ref< const Eigen::VectorXd > &diagonal, const Eigen::Ref< const Eigen::MatrixXd > &basis, Eigen::VectorXd &evals, Eigen::MatrixXd &evecs)
bool looCalibrationIsUnityFromCholeskyDiagonal(const Eigen::VectorXd &alpha, const Eigen::VectorXd &diagonal)
double looVarianceCalibrationFactor(const Eigen::VectorXd &alpha, const Eigen::VectorXd &inv_diag)
bool stabilizePosteriorCovariance(Eigen::MatrixXd &covariance)
Project a rounded covariance onto the positive-semidefinite cone while preserving its nonnegative dia...
static long factorization_rows
static double eigensolve_seconds
static int factorization_count
static double factorization_seconds
Eigen::Matrix< Extended, Eigen::Dynamic, 1 > ExtendedVector
Eigen::Matrix< Extended, Eigen::Dynamic, Eigen::Dynamic > ExtendedMatrix
gpr::extended::WorkingReal Extended
gpr::extended::WorkingReal Extended
Eigen::Matrix< Extended, Eigen::Dynamic, Eigen::Dynamic > ExtendedMatrix
What floorCertifiedSchurDiagonal did to a diagonal.
Eigen::Index proven_negative