7#include <Eigen/Cholesky>
8#include <Eigen/Eigenvalues>
18std::uint64_t splitmix64(std::uint64_t& state)
20 std::uint64_t
z = (state += 0x9E3779B97F4A7C15ULL);
21 z = (
z ^ (
z >> 30)) * 0xBF58476D1CE4E5B9ULL;
22 z = (
z ^ (
z >> 27)) * 0x94D049BB133111EBULL;
26double unitOpen(std::uint64_t bits)
28 return (
static_cast<double>(bits >> 11) + 0.5) * 0x1.0p-53;
35 const Eigen::MatrixXd& B,
38 const Eigen::Index n = B.rows(), m = B.cols();
40 throw std::invalid_argument(
"batch CG dimension mismatch");
42 out.X = Eigen::MatrixXd::Zero(n, m);
43 out.step.assign(
static_cast<std::size_t
>(m), {});
44 out.update.assign(
static_cast<std::size_t
>(m), {});
45 Eigen::MatrixXd R = B;
46 Eigen::MatrixXd Z = P.
solve(R);
47 Eigen::MatrixXd D = Z;
48 Eigen::VectorXd rz = (R.array() * Z.array()).colwise().sum().transpose();
49 out.initial_norm = rz;
50 out.residual_norm = R.colwise().norm().transpose();
51 std::vector<bool> active(
static_cast<std::size_t
>(m));
52 for (Eigen::Index j = 0; j < m; ++j)
53 active[
static_cast<std::size_t
>(j)] =
55 const double per_iteration =
61 for (
const bool a: active)
69 out.flops += per_iteration;
71 for (Eigen::Index j = 0; j < m; ++j) {
72 const auto s =
static_cast<std::size_t
>(j);
73 if (!active[s])
continue;
74 const double curvature = D.col(j).dot(KD.col(j));
75 if (!(curvature > 0.0)) {
77 out.residual_norm(j) = std::numeric_limits<double>::infinity();
80 const double a = rz(j) / curvature;
81 out.X.col(j).noalias() += a * D.col(j);
82 R.col(j).noalias() -= a * KD.col(j);
83 out.step[s].push_back(a);
84 out.residual_norm(j) = R.col(j).norm();
91 for (Eigen::Index j = 0; j < m; ++j) {
92 const auto s =
static_cast<std::size_t
>(j);
93 if (!active[s])
continue;
94 const double rz_new = R.col(j).dot(Z.col(j));
95 const double b = rz_new / rz(j);
97 out.update[s].push_back(b);
98 D.col(j) = Z.col(j) + b * D.col(j);
101 for (Eigen::Index j = 0; j < m; ++j)
103 out.converged =
false;
110double lanczosQuadrature(
const BatchSolve& solve, Eigen::Index column, F f)
112 const auto s =
static_cast<std::size_t
>(column);
113 const auto& a = solve.step[s];
114 const auto& b = solve.update[s];
115 const Eigen::Index k =
static_cast<Eigen::Index
>(a.size());
116 if (k == 0)
return std::numeric_limits<double>::quiet_NaN();
117 Eigen::VectorXd diagonal(k);
118 Eigen::VectorXd off(std::max<Eigen::Index>(k - 1, 0));
119 for (Eigen::Index i = 0; i < k; ++i) {
120 const auto u =
static_cast<std::size_t
>(i);
121 diagonal(i) = 1.0 / a[u];
122 if (i > 0) diagonal(i) += b[u - 1] / a[u - 1];
123 if (i + 1 < k) off(i) = std::sqrt(b[u]) / a[u];
125 Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> eigen;
126 eigen.computeFromTridiagonal(diagonal, off, Eigen::ComputeEigenvectors);
127 if (eigen.info() != Eigen::Success ||
128 !(eigen.eigenvalues().array() > 0.0).all())
129 return std::numeric_limits<double>::quiet_NaN();
130 const Eigen::VectorXd first = eigen.eigenvectors().row(0).transpose();
132 for (Eigen::Index i = 0; i < k; ++i)
133 sum += first(i) * first(i) * f(eigen.eigenvalues()(i));
134 return solve.initial_norm(column) * sum;
141 return lanczosQuadrature(solve, column,
142 [](
double x) {
return std::log(
x); });
147 return lanczosQuadrature(solve, column, [](
double x) {
148 const double l = std::log(
x);
156 Eigen::MatrixXd G(rows, cols);
157 std::uint64_t state = seed;
158 for (Eigen::Index j = 0; j < cols; ++j) {
159 for (Eigen::Index i = 0; i < rows; i += 2) {
160 const double u1 = unitOpen(splitmix64(state));
161 const double u2 = unitOpen(splitmix64(state));
162 const double radius = std::sqrt(-2.0 * std::log(u1));
163 const double angle = 2.0 * std::numbers::pi * u2;
164 G(i, j) = radius * std::cos(angle);
165 if (i + 1 < rows) G(i + 1, j) = radius * std::sin(angle);
174 if (!(target > 0.0) || !std::isfinite(sample_variance))
175 return std::numeric_limits<Eigen::Index>::max();
176 const double needed = std::ceil(sample_variance / (target * target));
177 if (needed >=
static_cast<double>(std::numeric_limits<Eigen::Index>::max()))
178 return std::numeric_limits<Eigen::Index>::max();
179 return std::max(taken,
static_cast<Eigen::Index
>(needed));
184 const Eigen::Index m = draws.size();
185 if (m < 2)
return std::numeric_limits<double>::infinity();
186 const double mean = draws.mean();
187 return (draws.array() - mean).square().sum() /
static_cast<double>(m - 1);
192 if (!(kappa >= 1.0) || !(tolerance > 0.0) || !std::isfinite(kappa))
193 return std::numeric_limits<double>::infinity();
194 if (tolerance >= 1.0)
return 1.0;
196 1.0, std::ceil(0.5 * std::sqrt(kappa) * std::log(2.0 / tolerance)));
200 const Eigen::VectorXd& start)
203 if (start.size() != K.
order())
204 throw std::invalid_argument(
"Lanczos start vector has the wrong order");
205 next_norm_ = start.norm();
206 if (!(next_norm_ > 0.0) || !std::isfinite(next_norm_))
207 throw std::invalid_argument(
"Lanczos start vector must be nonzero");
208 next_ = start / next_norm_;
209 Q_.resize(K.
order(), 0);
212bool LanczosVarianceCache::extend()
214 const Eigen::Index n = K_.
order(), k =
steps();
215 if (exhausted_ || k >= n)
return false;
216 Q_.conservativeResize(n, k + 1);
219 K_.
apply(Q_.col(k), w);
220 const double a = Q_.col(k).dot(w.col(0));
222 Eigen::VectorXd v = w.col(0);
223 for (
int pass = 0; pass < 2; ++pass)
224 v.noalias() -= Q_ * (Q_.transpose() * v);
225 const double b = v.norm();
227 flops_ += K_.
applyFlops(1) + 8.0 *
static_cast<double>(n * (k + 1));
228 if (!(b > std::numeric_limits<double>::epsilon() * std::abs(a))) {
239LanczosVarianceCache::Quadratic LanczosVarianceCache::evaluate(
240 const Eigen::MatrixXd& C,
double lambda_min)
const
242 const Eigen::Index k =
steps(), m = C.cols();
244 out.value = Eigen::VectorXd::Zero(m);
245 out.error_bound = C.colwise().squaredNorm().transpose() / lambda_min;
246 if (k == 0)
return out;
247 Eigen::MatrixXd T = Eigen::MatrixXd::Zero(k, k);
248 for (Eigen::Index i = 0; i < k; ++i) {
249 T(i, i) = alpha_[
static_cast<std::size_t
>(i)];
251 T(i, i + 1) = T(i + 1, i) = beta_[
static_cast<std::size_t
>(i)];
253 const Eigen::LLT<Eigen::MatrixXd> llt(T);
254 if (llt.info() != Eigen::Success)
return out;
255 const Eigen::MatrixXd G = Q_.transpose() * C;
256 const Eigen::MatrixXd Y = llt.solve(G);
257 out.value = (G.array() * Y.array()).colwise().sum().transpose();
258 Eigen::MatrixXd R = C - Q_ * G;
259 const double last = exhausted_ ? 0.0 : beta_.back();
260 R.noalias() -= (last * next_) * Y.row(k - 1);
261 out.error_bound = R.colwise().squaredNorm().transpose() / lambda_min;
262 out.flops = 6.0 *
static_cast<double>(C.rows() * k * m) +
263 static_cast<double>(k * k * k) / 3.0 +
264 4.0 *
static_cast<double>(k * k * m);
269 const Eigen::MatrixXd& C,
double tolerance,
double lambda_min,
272 if (C.rows() != K_.order() || !(lambda_min > 0.0))
273 throw std::invalid_argument(
"invalid Lanczos variance query");
274 const double start_flops = flops_;
275 double spent_on_queries = 0.0;
277 spent_on_queries +=
out.flops;
280 Eigen::Index target = std::max<Eigen::Index>(1,
steps());
281 while (!(
out.error_bound.maxCoeff() <= tolerance)) {
282 target = std::min<Eigen::Index>(K_.order(), 2 * target);
283 const double step_flops =
284 K_.applyFlops(1) + 8.0 *
static_cast<double>(K_.order() * target);
286 while (
steps() < target) {
287 if (flops_ - start_flops + spent_on_queries + step_flops >
290 if (!extend())
break;
294 out = evaluate(C, lambda_min);
295 spent_on_queries +=
out.flops;
296 if (exhausted_ ||
steps() >= K_.order())
break;
298 out.within_tolerance =
out.error_bound.maxCoeff() <= tolerance;
299 out.flops = flops_ - start_flops + spent_on_queries;
Quadratic quadraticDiagonal(const Eigen::MatrixXd &C, double tolerance, double lambda_min, double flop_budget)
LanczosVarianceCache(const SymmetricOperator &K, const Eigen::VectorXd &start)
Eigen::Index steps() const noexcept
double solveFlops(Eigen::Index rhs) const
Eigen::Index order() const noexcept
Eigen::MatrixXd solve(const Eigen::MatrixXd &X) const
P^{-1} X by Woodbury.
virtual void apply(const Eigen::MatrixXd &X, Eigen::MatrixXd &Y) const =0
Y = A X, X with order() rows and any number of columns.
virtual Eigen::Index order() const =0
virtual double applyFlops(Eigen::Index rhs) const =0
Floating-point operations of one apply to rhs columns.
eon_relax_band_t eon_relax_surface_fn void eon_relax_outcome_t * out
BatchSolve batchConjugateGradients(const SymmetricOperator &K, const PivotedCholeskyPreconditioner &P, const Eigen::MatrixXd &B, const BatchSolveSettings &settings)
double conjugateGradientIterations(double kappa, double tolerance)
double lanczosLogQuadrature(const BatchSolve &solve, Eigen::Index column)
double sampleVariance(const Eigen::VectorXd &draws)
Eigen::Index probesForStandardError(double sample_variance, double target, Eigen::Index taken)
double lanczosSquaredLogQuadrature(const BatchSolve &solve, Eigen::Index column)
Eigen::MatrixXd standardNormalProbes(Eigen::Index rows, Eigen::Index cols, std::uint64_t seed)
double flop_budget
Operations after which the solve gives up unconverged.
Eigen::VectorXd tolerance
Absolute residual 2-norm each column must reach.