Preconditioned CG on K X = B, all columns advanced by one block apply per iteration until each meets its tolerance or the budget is spent.
37{
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 =
58 Eigen::MatrixXd KD;
59 for (;;) {
60 bool any = false;
61 for (const bool a: active)
62 any = any || a;
63 if (!any) {
65 break;
66 }
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)) {
76 active[s] = false;
77 out.residual_norm(j) = std::numeric_limits<double>::infinity();
78 continue;
79 }
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();
86 active[s] = false;
87 continue;
88 }
89 }
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);
96 rz(j) = rz_new;
97 out.update[s].push_back(b);
98 D.col(j) = Z.col(j) + b * D.col(j);
99 }
100 }
101 for (Eigen::Index j = 0; j < m; ++j)
103 out.converged =
false;
105}
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
double flop_budget
Operations after which the solve gives up unconverged.
Eigen::VectorXd tolerance
Absolute residual 2-norm each column must reach.