Sleipnir C++ API
Loading...
Searching...
No Matches
sparse_kkt_solver.hpp
1// Copyright (c) Sleipnir contributors
2
3#pragma once
4
5#include <algorithm>
6#include <cmath>
7#include <limits>
8
9#include <Eigen/Core>
10#include <Eigen/SparseCholesky>
11#include <Eigen/SparseCore>
12
13#include "sleipnir/optimization/solver/util/regularization_limits.hpp"
14#include "sleipnir/optimization/solver/util/ruiz_equilibration.hpp"
15
16namespace slp {
17
23template <typename Scalar>
25 public:
27 using DenseVector = Eigen::VectorX<Scalar>;
29 using SparseMatrix = Eigen::SparseMatrix<Scalar>;
30
37 SparseKKTSolver(int num_decision_variables, int num_equality_constraints)
38 : m_num_decision_variables{num_decision_variables},
39 m_num_equality_constraints{num_equality_constraints} {}
40
44 Eigen::ComputationInfo info() const { return m_info; }
45
54 // Regularization with zeros ensures the pattern analysis in the sparse
55 // solver is reused by all factorizations
56 m_lhs = lhs + regularization(Scalar(0), Scalar(0));
57
58 if (!m_analyzed_pattern) {
59 m_scaled_lhs = m_lhs;
60 m_solver.analyzePattern(m_scaled_lhs);
61 m_analyzed_pattern = true;
62 }
63
64 // Threshold pivoting with 2x2 blocks is stable for indefinite matrices in
65 // practice, so the unregularized system is accepted whenever its inertia is
66 // ideal
67 factorize();
68 if (m_info == Eigen::Success && has_ideal_inertia()) {
69 m_prev_δ = Scalar(0);
70 m_prev_γ = Scalar(0);
71 return *this;
72 }
73
74 // We'll give lhs the correct inertia by adding [δI, 0; 0, −γI] where δ and
75 // γ regularize the Hessian and equality constraint Jacobian respectively.
76
77 // The minimum nonzero Hessian regularization
79
80 // The maximum constraint regularization. Larger values distort the equality
81 // constraint Jacobian more than they help a rank-deficient one.
83
84 // The initial nonzero constraint regularization
86
87 // If the previous δ was zero, attempt a small value. Otherwise, attempt a
88 // smaller value than the previous δ so δ trends downward. δ has a floor
89 // because when regularization is needed, δ is the only curvature in some
90 // directions, so the KKT matrix's smallest eigenvalues shrink with δ. Too
91 // small a δ makes the matrix ill-conditioned, which amplifies the
92 // factorization's rounding error in the solution, and eventually makes the
93 // factorization's pivots near-singular.
94 Scalar δ = m_prev_δ == Scalar(0) ? Scalar(1e-4)
95 : std::max(m_prev_δ / Scalar(2), δ_min);
96
97 // Start γ at zero to avoid distorting the equality constraint Jacobian. It
98 // only needs to be nonzero if the Jacobian turns out to be rank-deficient.
99 Scalar γ(0);
100
101 while (true) {
102 m_lhs = lhs + regularization(δ, γ);
103 factorize();
104
105 if (m_info == Eigen::Success) {
106 if (has_near_singular_pivot()) {
107 if (γ == Scalar(0)) {
108 // If there's a near-singular pivot and γ = 0, increase γ to
109 // potentially compensate for a rank-deficient equality constraint
110 // Jacobian
111 γ = γ_initial;
112 } else {
113 // If there's a near-singular pivot and γ > 0, increase δ and γ to
114 // move all pivots away from singularity
115 δ *= Scalar(10);
116 γ = std::min(γ * Scalar(10), γ_max);
117 }
118 } else if (m_solver.numNegative() > m_num_equality_constraints) {
119 // If there's too many negative eigenvalues, increase δ to add more
120 // positive eigenvalues
121 δ *= Scalar(10);
122 } else if (m_solver.numPositive() > m_num_decision_variables) {
123 // The KKT matrix has at least as many negative eigenvalues as
124 // equality constraints if γ > 0 (from the −γI block) or if the
125 // equality constraint Jacobian has full row rank. Too many positive
126 // eigenvalues can then only come from rounding error, so increase δ
127 // and γ to drive all eigenvalues away from zero.
128 δ *= Scalar(10);
129 γ = γ == Scalar(0) ? γ_initial : std::min(γ * Scalar(10), γ_max);
130 } else {
131 // If the inertia is ideal, report success
132 m_prev_δ = δ;
133 m_prev_γ = γ;
134 return *this;
135 }
136 } else {
137 // If the factorization failed, increase δ and γ to drive all
138 // eigenvalues away from zero
139 δ *= Scalar(10);
140 γ = γ == Scalar(0) ? γ_initial : std::min(γ * Scalar(10), γ_max);
141 }
142
143 // If the lhs perturbation is too high, report failure. This can be caused
144 // by ill-conditioning.
145 if (δ > Scalar(1e20) || γ > Scalar(1e20)) {
146 m_info = Eigen::NumericalIssue;
147 m_prev_δ = δ;
148 m_prev_γ = γ;
149 return *this;
150 }
151 }
152 }
153
158 template <typename Rhs>
159 DenseVector solve(const Eigen::MatrixBase<Rhs>& rhs) const {
160 using std::pow;
161
162 DenseVector x = solve_factorized(rhs);
163
164 // The factorization is stable, but the matrix's conditioning amplifies its
165 // rounding error in the solution, so apply iterative refinement with the
166 // same factorization
167 constexpr int max_refinement_steps = 3;
168
169 // Stop once the relative residual is ε^(3/4), which is halfway (on a log
170 // scale) between the solver's default tolerance of √ε and the
171 // factorization's rounding error floor of a small multiple of ε
172 const Scalar refinement_tolerance =
173 pow(std::numeric_limits<Scalar>::epsilon(), Scalar(0.75));
174
175 for (int i = 0; i < max_refinement_steps; ++i) {
176 DenseVector r = rhs - m_lhs.template selfadjointView<Eigen::Lower>() * x;
177 if (r.norm() <= refinement_tolerance * rhs.norm()) {
178 break;
179 }
180 x += solve_factorized(r);
181 }
182
183 return x;
184 }
185
190 template <typename Rhs>
191 DenseVector solve(const Eigen::SparseMatrixBase<Rhs>& rhs) const {
192 return solve(rhs.toDense());
193 }
194
198 Scalar hessian_regularization() const { return m_prev_δ; }
199
203 Scalar constraint_jacobian_regularization() const { return m_prev_γ; }
204
205 private:
206 using Solver = Eigen::MultifrontalLDLT<SparseMatrix, Eigen::Lower>;
207
208 Solver m_solver;
209 bool m_analyzed_pattern = false;
210
212 SparseMatrix m_lhs;
213
215 SparseMatrix m_scaled_lhs;
216
218 RuizEquilibration<Scalar> m_equilibration;
219
220 Eigen::ComputationInfo m_info = Eigen::Success;
221
223 int m_num_decision_variables = 0;
224
226 int m_num_equality_constraints = 0;
227
229 Scalar m_prev_δ{0};
230
232 Scalar m_prev_γ{0};
233
241 void factorize() {
242 m_equilibration.compute(m_lhs);
243 m_equilibration.apply(m_lhs, m_scaled_lhs);
244 m_solver.factorize(m_scaled_lhs);
245 m_info = m_solver.info();
246 }
247
252 DenseVector solve_factorized(const DenseVector& rhs) const {
253 const auto& S = m_equilibration.scale();
254 DenseVector x = m_solver.solve(rhs.cwiseProduct(S));
255 x.array() *= S.array();
256 return x;
257 }
258
264 bool has_ideal_inertia() const {
265 return !has_near_singular_pivot() &&
266 m_solver.numPositive() == m_num_decision_variables &&
267 m_solver.numNegative() == m_num_equality_constraints;
268 }
269
275 bool has_near_singular_pivot() const {
276 using std::abs;
277 using std::hypot;
278
279 const Scalar threshold = near_singular_pivot_threshold<Scalar>();
280
281 const auto& D = m_solver.vectorD();
282 const auto& D_sub = m_solver.subDiagonal();
283 const auto& rows = m_solver.permutationPinv().indices();
284 const auto& S = m_equilibration.scale();
285
286 // This treats NaN as near zero
287 auto is_near_zero = [&](Scalar λ) { return !(abs(λ) > threshold); };
288
289 // Check each of D's 1x1 and 2x2 pivots for near-singularity
290 for (int k = 0; k < D.size(); ++k) {
291 const Scalar s = S[rows[k]];
292 if (D_sub[k] != Scalar(0)) {
293 const Scalar s_next = S[rows[k + 1]];
294
295 // The eigenvalues of the 2x2 block [a b; b c] are the roots of its
296 // characteristic polynomial.
297 //
298 // det([a − λ b; b c − λ]) = (a − λ)(c − λ) − b²
299 // = λ² − (a + c)λ + (ac − b²)
300 //
301 // λ = (a + c)/2 ± r where r = √(((a − c)/2)² + b²)
302 //
303 // Let λ₁ be the root farther from zero, so only the other root λ₂ needs
304 // checking. λ₁'s two terms have the same sign, so it has no
305 // cancellation. The two terms of λ₂ have opposite signs, so λ₂ loses
306 // accuracy if |a| >> |c|. Instead, compute λ₂ from λ₁ and the product
307 // of the roots.
308 //
309 // λ₁λ₂ = ((a + c)/2 + r)((a + c)/2 − r)
310 // λ₂ = (a/λ₁)c − (b/λ₁)b
311 //
312 // The factorization is of S lhs S, so we unscale D's entries by S so
313 // the threshold is applied to lhs's pivots instead.
314 const Scalar a = D[k] / (s * s);
315 const Scalar b = D_sub[k] / (s * s_next);
316 const Scalar c = D[k + 1] / (s_next * s_next);
317 const Scalar mid = (a + c) / Scalar(2);
318 const Scalar r = hypot((a - c) / Scalar(2), abs(b));
319 const Scalar λ = mid >= Scalar(0) ? mid + r : mid - r;
320 if (is_near_zero((a / λ) * c - (b / λ) * b)) {
321 return true;
322 }
323 ++k;
324 } else if (is_near_zero(D[k] / (s * s))) {
325 return true;
326 }
327 }
328
329 return false;
330 }
331
340 SparseMatrix regularization(Scalar δ, Scalar γ) const {
341 DenseVector vec{m_num_decision_variables + m_num_equality_constraints};
342 vec.segment(0, m_num_decision_variables).setConstant(δ);
343 vec.segment(m_num_decision_variables, m_num_equality_constraints)
344 .setConstant(-γ);
345
346 return SparseMatrix{vec.asDiagonal()};
347 }
348};
349
350} // namespace slp
Definition intrusive_shared_ptr.hpp:27
Definition sparse_kkt_solver.hpp:24
Scalar constraint_jacobian_regularization() const
Definition sparse_kkt_solver.hpp:203
SparseKKTSolver(int num_decision_variables, int num_equality_constraints)
Definition sparse_kkt_solver.hpp:37
Eigen::VectorX< Scalar > DenseVector
Type alias for dense vector.
Definition sparse_kkt_solver.hpp:27
DenseVector solve(const Eigen::MatrixBase< Rhs > &rhs) const
Definition sparse_kkt_solver.hpp:159
Scalar hessian_regularization() const
Definition sparse_kkt_solver.hpp:198
Eigen::ComputationInfo info() const
Definition sparse_kkt_solver.hpp:44
Eigen::SparseMatrix< Scalar > SparseMatrix
Type alias for sparse matrix.
Definition sparse_kkt_solver.hpp:29
DenseVector solve(const Eigen::SparseMatrixBase< Rhs > &rhs) const
Definition sparse_kkt_solver.hpp:191
SparseKKTSolver & compute(const SparseMatrix &lhs)
Definition sparse_kkt_solver.hpp:53