Sleipnir C++ API
Loading...
Searching...
No Matches
dense_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/Cholesky>
10#include <Eigen/Core>
11
12#include "sleipnir/optimization/solver/util/regularization_limits.hpp"
13
14namespace slp {
15
21template <typename Scalar>
23 public:
25 using DenseMatrix = Eigen::MatrixX<Scalar>;
27 using DenseVector = Eigen::VectorX<Scalar>;
28
35 DenseKKTSolver(int num_decision_variables, int num_equality_constraints)
36 : m_num_decision_variables{num_decision_variables},
37 m_num_equality_constraints{num_equality_constraints} {}
38
42 Eigen::ComputationInfo info() const { return m_info; }
43
49 // Bunch-Kaufman pivoting is backward stable for indefinite matrices, so the
50 // unregularized system is accepted whenever its inertia is ideal
51 m_lhs = lhs;
52 factorize();
53 if (m_info == Eigen::Success && has_ideal_inertia()) {
54 m_prev_δ = Scalar(0);
55 m_prev_γ = Scalar(0);
56 return *this;
57 }
58
59 // We'll give lhs the correct inertia by adding [δI, 0; 0, −γI] where δ and
60 // γ regularize the Hessian and equality constraint Jacobian respectively.
61
62 // The minimum nonzero Hessian regularization
64
65 // The maximum constraint regularization. Larger values distort the equality
66 // constraint Jacobian more than they help a rank-deficient one.
68
69 // The initial nonzero constraint regularization
71
72 // If the previous δ was zero, attempt a small value. Otherwise, attempt a
73 // smaller value than the previous δ so δ trends downward. δ has a floor
74 // because when regularization is needed, δ is the only curvature in some
75 // directions, so the KKT matrix's smallest eigenvalues shrink with δ. Too
76 // small a δ makes the matrix ill-conditioned, which amplifies the
77 // factorization's rounding error in the solution, and eventually makes the
78 // factorization's pivots near-singular.
79 Scalar δ = m_prev_δ == Scalar(0) ? Scalar(1e-4)
80 : std::max(m_prev_δ / Scalar(2), δ_min);
81
82 // Start γ at zero to avoid distorting the equality constraint Jacobian. It
83 // only needs to be nonzero if the Jacobian turns out to be rank-deficient.
84 Scalar γ(0);
85
86 while (true) {
87 m_lhs = lhs + regularization(δ, γ);
88 factorize();
89
90 if (m_info == Eigen::Success) {
91 if (has_near_singular_pivot()) {
92 if (γ == Scalar(0)) {
93 // If there's a near-singular pivot and γ = 0, increase γ to
94 // potentially compensate for a rank-deficient equality constraint
95 // Jacobian
96 γ = γ_initial;
97 } else {
98 // If there's a near-singular pivot and γ > 0, increase δ and γ to
99 // move all pivots away from singularity
100 δ *= Scalar(10);
101 γ = std::min(γ * Scalar(10), γ_max);
102 }
103 } else if (m_solver.numNegative() > m_num_equality_constraints) {
104 // If there's too many negative eigenvalues, increase δ to add more
105 // positive eigenvalues
106 δ *= Scalar(10);
107 } else if (m_solver.numPositive() > m_num_decision_variables) {
108 // The KKT matrix has at least as many negative eigenvalues as
109 // equality constraints if γ > 0 (from the −γI block) or if the
110 // equality constraint Jacobian has full row rank. Too many positive
111 // eigenvalues can then only come from rounding error, so increase δ
112 // and γ to drive all eigenvalues away from zero.
113 δ *= Scalar(10);
114 γ = γ == Scalar(0) ? γ_initial : std::min(γ * Scalar(10), γ_max);
115 } else {
116 // If the inertia is ideal, report success
117 m_prev_δ = δ;
118 m_prev_γ = γ;
119 return *this;
120 }
121 } else {
122 // If the factorization failed, increase δ and γ to drive all
123 // eigenvalues away from zero
124 δ *= Scalar(10);
125 γ = γ == Scalar(0) ? γ_initial : std::min(γ * Scalar(10), γ_max);
126 }
127
128 // If the lhs perturbation is too high, report failure. This can be caused
129 // by ill-conditioning.
130 if (δ > Scalar(1e20) || γ > Scalar(1e20)) {
131 m_info = Eigen::NumericalIssue;
132 m_prev_δ = δ;
133 m_prev_γ = γ;
134 return *this;
135 }
136 }
137 }
138
143 template <typename Rhs>
144 DenseVector solve(const Eigen::MatrixBase<Rhs>& rhs) const {
145 using std::pow;
146
147 DenseVector x = solve_factorized(rhs);
148
149 // The factorization is backward stable, but the matrix's conditioning
150 // amplifies its rounding error in the solution, so apply iterative
151 // refinement with the same factorization
152 constexpr int max_refinement_steps = 3;
153
154 // Stop once the relative residual is ε^(3/4), which is halfway (on a log
155 // scale) between the solver's default tolerance of √ε and the
156 // factorization's rounding error floor of a small multiple of ε
157 const Scalar refinement_tolerance =
158 pow(std::numeric_limits<Scalar>::epsilon(), Scalar(0.75));
159
160 for (int i = 0; i < max_refinement_steps; ++i) {
161 DenseVector r = rhs - m_lhs.template selfadjointView<Eigen::Lower>() * x;
162 if (r.norm() <= refinement_tolerance * rhs.norm()) {
163 break;
164 }
165 x += solve_factorized(r);
166 }
167
168 return x;
169 }
170
175 template <typename Rhs>
176 DenseVector solve(const Eigen::SparseMatrixBase<Rhs>& rhs) const {
177 return solve(rhs.toDense());
178 }
179
183 Scalar hessian_regularization() const { return m_prev_δ; }
184
188 Scalar constraint_jacobian_regularization() const { return m_prev_γ; }
189
190 private:
191 using Solver = Eigen::BunchKaufman<DenseMatrix>;
192
193 Solver m_solver;
194
196 DenseMatrix m_lhs;
197
198 Eigen::ComputationInfo m_info = Eigen::Success;
199
201 int m_num_decision_variables = 0;
202
204 int m_num_equality_constraints = 0;
205
207 Scalar m_prev_δ{0};
208
210 Scalar m_prev_γ{0};
211
213 void factorize() { m_info = m_solver.compute(m_lhs).info(); }
214
219 DenseVector solve_factorized(const DenseVector& rhs) const {
220 return m_solver.solve(rhs);
221 }
222
228 bool has_ideal_inertia() const {
229 return !has_near_singular_pivot() &&
230 m_solver.numPositive() == m_num_decision_variables &&
231 m_solver.numNegative() == m_num_equality_constraints;
232 }
233
239 bool has_near_singular_pivot() const {
240 using std::abs;
241 using std::hypot;
242
243 const Scalar threshold = near_singular_pivot_threshold<Scalar>();
244
245 const auto& D = m_solver.vectorD();
246 const auto& D_sub = m_solver.subDiagonal();
247
248 // This treats NaN as near zero
249 auto is_near_zero = [&](Scalar λ) { return !(abs(λ) > threshold); };
250
251 // Check each of D's 1x1 and 2x2 pivots for near-singularity
252 for (int k = 0; k < D.size(); ++k) {
253 if (D_sub[k] != Scalar(0)) {
254 // The eigenvalues of the 2x2 block [a b; b c] are the roots of its
255 // characteristic polynomial.
256 //
257 // det([a − λ b; b c − λ]) = (a − λ)(c − λ) − b²
258 // = λ² − (a + c)λ + (ac − b²)
259 //
260 // λ = (a + c)/2 ± r where r = √(((a − c)/2)² + b²)
261 //
262 // Let λ₁ be the root farther from zero, so only the other root λ₂ needs
263 // checking. λ₁'s two terms have the same sign, so it has no
264 // cancellation. The two terms of λ₂ have opposite signs, so λ₂ loses
265 // accuracy if |a| >> |c|. Instead, compute λ₂ from λ₁ and the product
266 // of the roots.
267 //
268 // λ₁λ₂ = ((a + c)/2 + r)((a + c)/2 − r)
269 // λ₂ = (a/λ₁)c − (b/λ₁)b
270 const Scalar a = D[k];
271 const Scalar b = D_sub[k];
272 const Scalar c = D[k + 1];
273 const Scalar mid = (a + c) / Scalar(2);
274 const Scalar r = hypot((a - c) / Scalar(2), abs(b));
275 const Scalar λ = mid >= Scalar(0) ? mid + r : mid - r;
276 if (is_near_zero((a / λ) * c - (b / λ) * b)) {
277 return true;
278 }
279 ++k;
280 } else if (is_near_zero(D[k])) {
281 return true;
282 }
283 }
284
285 return false;
286 }
287
296 DenseMatrix regularization(Scalar δ, Scalar γ) const {
297 DenseVector vec{m_num_decision_variables + m_num_equality_constraints};
298 vec.segment(0, m_num_decision_variables).setConstant(δ);
299 vec.segment(m_num_decision_variables, m_num_equality_constraints)
300 .setConstant(-γ);
301
302 return vec.asDiagonal().toDenseMatrix();
303 }
304};
305
306} // namespace slp
Definition dense_kkt_solver.hpp:22
Scalar constraint_jacobian_regularization() const
Definition dense_kkt_solver.hpp:188
Scalar hessian_regularization() const
Definition dense_kkt_solver.hpp:183
Eigen::ComputationInfo info() const
Definition dense_kkt_solver.hpp:42
DenseKKTSolver(int num_decision_variables, int num_equality_constraints)
Definition dense_kkt_solver.hpp:35
Eigen::VectorX< Scalar > DenseVector
Type alias for dense vector.
Definition dense_kkt_solver.hpp:27
Eigen::MatrixX< Scalar > DenseMatrix
Type alias for dense matrix.
Definition dense_kkt_solver.hpp:25
DenseVector solve(const Eigen::SparseMatrixBase< Rhs > &rhs) const
Definition dense_kkt_solver.hpp:176
DenseVector solve(const Eigen::MatrixBase< Rhs > &rhs) const
Definition dense_kkt_solver.hpp:144
DenseKKTSolver & compute(const DenseMatrix &lhs)
Definition dense_kkt_solver.hpp:48
Definition intrusive_shared_ptr.hpp:27